- Developing Middleware in Java EE 8
- Abdalla Mahmoud
- 147字
- 2021-07-23 19:24:34
Bean constructor parameter injection
Constructor injection is another mechanism for injecting CDI beans. By bean constructor parameter injection, we can use constructor parameters as injection points for our CDI beans. One major advantage of constructor injection is that it allows the bean to be immutable.
Look at the following MyPojo bean:
@Dependent public class MyPojo { public String getMessage() { return "Hello from MyPojo!"; } }
We will get it injected using constructor parameters in AnotherPojo:
@Dependent public class AnotherPojo { private MyPojo myPojo; @Inject public AnotherPojo(MyPojo myPojo) { this.myPojo = myPojo; } public String getMessage() { return myPojo.getMessage(); } }
As you can see, the AnotherPojo's constructor is annotated with @Inject; this tells the container that this constructor holds parameters of injection points, which need to be satisfied during bean instantiation. Note that only one constructor can be used as an injection point in CDI beans.
推薦閱讀