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

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.

主站蜘蛛池模板: 关岭| 塔河县| 军事| 内江市| 德州市| 平乡县| 永川市| 肇源县| 城步| 盘锦市| 武宣县| 应城市| 山阳县| 岢岚县| 阿克| 阳西县| 韶关市| 大庆市| 柳江县| 江山市| 肥西县| 清水县| 肥城市| 开原市| 刚察县| 内乡县| 葵青区| 邵东县| 永胜县| 左贡县| 望都县| 扎兰屯市| 贞丰县| 松滋市| 驻马店市| 崇左市| 咸宁市| 竹山县| 安徽省| 玉环县| 榆社县|