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

Injection into the producer methods

In the previous example, we have instantiated our bean inside the producer method using the Java new keyword. This is useful, as mentioned earlier when we need to use plain Java objects as CDI beans. However, if we want to make use of great CDI features, such as dependency injection and interceptors, we need to return a real CDI bean. To do this, we will rewrite our producer method as follows:

@SessionScoped 
public class Preferences implements Serializable { 
    ... 
    @Produces 
    @Preferred 
    @RequestScoped 
    public PaymentStrategy getPaymentStrategy(CreditCardPaymentStrategy ccps, 
            CheckPaymentStrategy cps, 
            PayPalPaymentStrategy ppps) { 
        switch (paymentStrategy) { 
            case CREDIT_CARD: 
                return ccps; 
 
            case CHECK: 
                return cps; 
 
            case PAYPAL: 
                return ppps; 
 
            default: 
                return null; 
        } 
    } 
} 

In this example, we have provided the producer method with three parameters of the three possible implementations of the PaymentStragey. Yes, this is dependency injection! The container will inject three instances of the different available payment strategies, and then you will return one of the user choices. The difference here is that the returned bean will be created using the container, rather than Java's new keyword, and hence, it will utilize all the great services provided to CDI beans.

主站蜘蛛池模板: 巩义市| 柞水县| 长乐市| 乌兰察布市| 高雄市| 长葛市| 滨州市| 隆昌县| 邵阳市| 醴陵市| 玛曲县| 田林县| 乡宁县| 深州市| 邵阳市| 军事| 鹤壁市| 普安县| 赤峰市| 罗田县| 汝城县| 洛隆县| 临城县| 萝北县| 祁门县| 广安市| 永登县| 景泰县| 留坝县| 南通市| 尚义县| 聂荣县| 汶上县| 霍山县| 巴里| 周口市| 汝城县| 天镇县| 崇左市| 西盟| 津南区|