- Developing Middleware in Java EE 8
- Abdalla Mahmoud
- 196字
- 2021-07-23 19:24:34
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.
- PHP 7底層設計與源碼實現
- 算法訓練營:入門篇(全彩版)
- PHP+MySQL網站開發技術項目式教程(第2版)
- 樂高機器人設計技巧:EV3結構設計與編程指導
- Mastering PHP Design Patterns
- Mastering matplotlib
- C/C++常用算法手冊(第3版)
- Python程序設計
- 移動界面(Web/App)Photoshop UI設計十全大補
- OpenStack Orchestration
- HTML5從入門到精通 (第2版)
- 零基礎學Scratch 3.0編程
- 面向對象程序設計及C++(第3版)
- Android嵌入式系統程序開發(基于Cortex-A8)
- Java 9:Building Robust Modular Applications