What is a CDI bean?

Yashar picture Yashar · Mar 20, 2013 · Viewed 25k times · Source

I am a little bit confused, we call CDI bean to the beans which we inject them using @Inject annotation or the beans which we use @Inject inside them ?

Answer

Mohanraj Balasubramaniam picture Mohanraj Balasubramaniam · May 3, 2017

CDI beans are classes that CDI can instantiate, manage, and inject automatically to satisfy the dependencies of other objects. Almost any Java class can be managed and injected by CDI.

For example, PrintServlet got dependency on a Message instance and have it injected automatically by the CDI runtime.

PrintServlet.java

@WebServlet("/printservlet")
public class PrintServlet extends HttpServlet {
    @Inject private Message message;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.getWriter().print(message.get());
    }
}

Message.java (This class is a CDI bean)

@RequestScoped
public class Message {
    @Override
    public String get() {
        return "Hello World!";
    }
}

Cheers!