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

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.

主站蜘蛛池模板: 沙雅县| 绥江县| 景泰县| 宝应县| 漠河县| 莱阳市| 南通市| 怀远县| 张家口市| 阳泉市| 临泉县| 汉寿县| 彰化县| 炉霍县| 司法| 扬州市| 碌曲县| 湖北省| 巴楚县| 绥滨县| 嵩明县| 常山县| 茌平县| 玉田县| 秦皇岛市| 霞浦县| 泰来县| 定日县| 佛坪县| 富源县| 赞皇县| 蓝田县| 定陶县| 顺昌县| 乌兰县| 敦化市| 水城县| 驻马店市| 车险| 涿鹿县| 密山市|