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

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.

主站蜘蛛池模板: 宁陵县| 邓州市| 淅川县| 云林县| 龙游县| 新密市| 云南省| 蒲江县| 措美县| 达日县| 奇台县| 乡宁县| 财经| 沂源县| 宜昌市| 扎兰屯市| 托克逊县| 肥城市| 县级市| 社旗县| 大足县| 五峰| 凌海市| 淳安县| 禹州市| 河南省| 梨树县| 绥棱县| 浑源县| 安多县| 惠水县| 息烽县| 东乡县| 普洱| 紫金县| 循化| 溧水县| 五家渠市| 四平市| 宁陵县| 弋阳县|