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

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.

主站蜘蛛池模板: 陇西县| 会同县| 平南县| 广东省| 腾冲县| 长白| 五指山市| 滕州市| 克拉玛依市| 内丘县| 建湖县| 饶阳县| 普兰县| 牡丹江市| 延川县| 伊春市| 东辽县| 易门县| 肥乡县| 玛纳斯县| 禹城市| 武义县| 江门市| 咸丰县| 日照市| 邵武市| 饶河县| 航空| 志丹县| 衢州市| 江安县| 阿克陶县| 滨海县| 罗源县| 萨迦县| 河间市| 肇庆市| 定结县| 汝城县| 公安县| 仙居县|