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

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.

主站蜘蛛池模板: 思茅市| 新河县| 金乡县| 扎赉特旗| 砀山县| 连云港市| 江口县| 普定县| 乐业县| 景谷| 名山县| 夹江县| 财经| 历史| 响水县| 舞阳县| 珠海市| 微博| 太和县| 凤山县| 芦溪县| 石景山区| 府谷县| 洛阳市| 鹤岗市| 郎溪县| 永宁县| 惠水县| 门源| 灵台县| 安康市| 旌德县| 应用必备| 镇巴县| 广平县| 镶黄旗| 石渠县| 蚌埠市| 和林格尔县| 东兰县| 汉沽区|