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:
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.