Injecting beans
As you saw in previous examples, the @Inject annotation allows us to inject a bean as a field in another bean during its instantiation. However, the use of @Inject is not limited to fields only, as there are three valid mechanisms for injecting CDI beans:
- Direct field injection
- Bean constructor parameter injection
- Initializer method parameter injection
Direct field injection
Direct field injection is almost the easiest and most common mechanism for injecting CDI beans. By direct field injection, we mean that we define the injection point as an instance variable within another bean, then we use the @Inject annotation to request dependency injection. We have already used this mechanism in previous examples, so just to recall its code:
@Dependent
public class AnotherPojo {
@Inject
private MyPojo myPojo;
...
} Bean constructor parameter injection
Constructor injection is another mechanism for injecting CDI beans. By bean constructor parameter injection, we can use...