- Developing Middleware in Java EE 8
- Abdalla Mahmoud
- 318字
- 2021-07-23 19:24:32
First CDI bean
In this example, we are going to do two steps:
- Defining a CDI bean
- Injecting and using the CDI bean
Start the first step by creating a new Java class with the name MyPojo, and then write the following code:
@Dependent public class MyPojo public String getMessage() { return "Hello from MyPojo !"; } }
In the previous code snippet, we have written our first CDI bean. As you likely noticed, the bean is nothing more than a plain old Java object, annotated with the @Dependent annotation. This annotation declares that our POJO is a CDI component, which is called the dependent scope. The dependent scope tells the CDI context that whenever we request an injection to this bean, a new instance will be created. The list of the other available scopes of CDI beans will be shown later, in the Using scopes section.
Now, let's move forward to the next step: injecting our baby CDI bean into another component. We are going to use a servlet as an example to this. Create a servlet named ExampleServlet and write the following code:
@WebServlet(urlPatterns = "/cdi-example-1") public class ExampleServlet extends HttpServlet { @Inject private MyPojo myPojo; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getOutputStream().println(myPojo.getMessage()); } }
As you can see, we have used the @Inject annotation to obtain an instance to the MyPojo class. Now run the application, and visit the following URL: http://localhost:8080/EnterpriseApplication1-war/cdi-example-1.
You should see a page with the following text:
Hello from MyPojo !
Congratulations! You have just created and used your first CDI bean. Although the previous example looks trivial, and it seems we did nothing more than create a new instance of a class (could be much easier to use Java's new keyword, right?). However, by reading the following sections, you will encounter more CDI features that will attract you to the CDI API.
- FuelPHP Application Development Blueprints
- JavaScript前端開發模塊化教程
- 基于粒計算模型的圖像處理
- Apache ZooKeeper Essentials
- Mastering PHP Design Patterns
- Learning AWS Lumberyard Game Development
- Java Web程序設計任務教程
- Python編程:從入門到實踐
- Keras深度學習實戰
- Mastering Unity 2D Game Development(Second Edition)
- 大學計算機基礎實驗指導
- C語言程序設計與應用實驗指導書(第2版)
- Instant GLEW
- JavaScript前端開發基礎教程
- iOS Development with Xamarin Cookbook