- 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.
- JavaScript百煉成仙
- 案例式C語言程序設計
- ReSharper Essentials
- 造個小程序:與微信一起干件正經事兒
- JavaScript 網頁編程從入門到精通 (清華社"視頻大講堂"大系·網絡開發視頻大講堂)
- Mastering Julia
- JS全書:JavaScript Web前端開發指南
- Mastering RStudio:Develop,Communicate,and Collaborate with R
- Elasticsearch for Hadoop
- 深入淺出Serverless:技術原理與應用實踐
- SQL Server 2016數據庫應用與開發
- 西門子S7-200 SMART PLC編程從入門到實踐
- Java面向對象程序設計
- C語言程序設計習題與實驗指導
- SQL Server 2008中文版項目教程(第3版)