官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 富锦市| 新郑市| 大厂| 松阳县| 子洲县| 资阳市| 恭城| 满城县| 曲周县| 泰宁县| 胶南市| 彩票| 静乐县| 聊城市| 宁阳县| 鄄城县| 陵水| 江西省| 沙河市| 郴州市| 东光县| 垣曲县| 琼海市| 萨迦县| 高州市| 马关县| 辽阳市| 新乡县| 全南县| 洛隆县| 紫云| 万全县| 丹东市| 云霄县| 越西县| 海阳市| 秦皇岛市| 临邑县| 砚山县| 绥棱县| 昭通市|