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

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.

主站蜘蛛池模板: 房产| 宿迁市| 上林县| 盘山县| 赫章县| 高尔夫| 绵阳市| 宁国市| 黑水县| 洛南县| 玛纳斯县| 于田县| 武邑县| 玉树县| 北川| 瑞丽市| 醴陵市| 壶关县| 通河县| 古浪县| 新沂市| 龙游县| 嵩明县| 鸡东县| 林州市| 通辽市| 堆龙德庆县| 洛阳市| 酒泉市| 肇东市| 杭锦旗| 齐齐哈尔市| 沾化县| 绿春县| 连平县| 九龙坡区| 九龙县| 天柱县| 伊金霍洛旗| 双鸭山市| 平阴县|