- Developing Middleware in Java EE 8
- Abdalla Mahmoud
- 147字
- 2021-07-23 19:24:34
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.
推薦閱讀
- TensorFlow Lite移動端深度學習
- C++ Builder 6.0下OpenGL編程技術
- Instant Zepto.js
- Visual Basic程序設計實驗指導(第4版)
- QGIS:Becoming a GIS Power User
- Python完全自學教程
- Java系統化項目開發教程
- iOS開發實戰:從入門到上架App Store(第2版) (移動開發叢書)
- Python機器學習:預測分析核心算法
- Visual Basic 6.0程序設計實驗教程
- 編寫高質量代碼:改善Objective-C程序的61個建議
- Vue.js光速入門及企業項目開發實戰
- Android Game Programming by Example
- SwiftUI極簡開發
- 軟件測試分析與實踐