Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Explanation of the @Inject Annotation

Header Image

Ahoy there, mateys! Welcome aboard our pirate-themed instructional website, where we make coding and development more approachable and enjoyable. Today, we’re going to be talking about CDI, or Contexts and Dependency Injection, and specifically how the @Inject annotation is used to inject dependencies into a CDI bean.

How the @Inject Annotation is Used to Inject Dependencies into a CDI Bean

Dependency injection is an important concept in software development as it allows for loose coupling and modular design. In CDI, we can use the @Inject annotation to inject dependencies into a CDI bean, making it easier to manage and use within our application.

Let’s say we have a Ship class that requires a Cannon object to function properly. Instead of creating a Cannon object within the Ship class, we can use the @Inject annotation to inject a Cannon object into the Ship class at runtime.

public class Ship {
  @Inject
  private Cannon cannon;
  
  // rest of the Ship class
}

In the code above, we have used the @Inject annotation to inject a Cannon object into the Ship class. When the Ship class is instantiated, the container will automatically provide a Cannon object and inject it into the cannon field. This allows us to separate the creation of the Cannon object from the Ship class, making it more modular and easier to maintain.

We can also use the @Inject annotation to inject dependencies into constructor methods, setter methods, and even private methods.

public class Ship {
  private Cannon cannon;
  
  @Inject
  public Ship(Cannon cannon) {
    this.cannon = cannon;
  }
  
  @Inject
  public void setCannon(Cannon cannon) {
    this.cannon = cannon;
  }
  
  private void prepareForBattle() {
    // do something with the cannon
  }
  
  @Inject
  private void setCaptain(Captain captain) {
    // do something with the captain
  }
  
  // rest of the Ship class
}

In the code above, we have used the @Inject annotation to inject a Cannon object into the Ship class’s constructor method, setter method, and private method. This allows us to inject dependencies into any part of the Ship class, making it more flexible and easier to manage.

To summarize, the @Inject annotation is used to inject dependencies into a CDI bean, allowing for loose coupling and modular design. We can use the @Inject annotation to inject dependencies into fields, constructor methods, setter methods, and even private methods.

Conclusion

Well, that’s all for now, me hearties! We hope you found this explanation of the @Inject annotation useful and informative. Remember to keep injecting those dependencies to keep your CDI beans shipshape and seaworthy!