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

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.

主站蜘蛛池模板: 恭城| 湾仔区| 宣化县| 柘荣县| 南安市| 淅川县| 南和县| 南郑县| 茌平县| 东乡县| 城固县| 鹰潭市| 鄢陵县| 丰城市| 嘉兴市| 苏尼特左旗| 娄烦县| 顺昌县| 康平县| 福建省| 日土县| 黔西县| 襄樊市| 宁波市| 锡林郭勒盟| 南昌市| 彭州市| 宣恩县| 民权县| 辉南县| 喀喇沁旗| 襄汾县| 汉中市| 武定县| 平舆县| 乌兰察布市| 黄大仙区| 临桂县| 赤城县| 上饶市| 玉门市|