Contexts and Dependency Injection (CDI) enables your objects to have
their dependencies provided to them automatically, instead of creating
them or receiving them as parameters. CDI also manages the lifecycle of
those dependencies for you.
For example, consider the following servlet:
@WebServlet("/cdiservlet")
public class NewServlet extends HttpServlet {
private Message message;
@Override
public void init() {
message = new MessageB();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.getWriter().write(message.get());
}
}
This servlet needs an instance of an object that implements the
Message
interface:
public interface Message {
public String get();
}
The servlet creates itself an instance of the following object:
public class MessageB implements Message {
public MessageB() { }
@Override
public String get() {
return "message B";
}
}
Using CDI, this servlet can declare its dependency on a Message
instance and have it injected automatically by the CDI runtime. The new
servlet code is the following:
@WebServlet("/cdiservlet")
public class NewServlet extends HttpServlet {
@Inject private Message message;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.getWriter().write(message.get());
}
}
The CDI runtime looks for classes that implement the Message
interface, finds the MessageB
class, creates a new instance of it, and
injects it into the servlet at runtime. To manage the lifecycle of the
new instance, the CDI runtime needs to know what the scope of the
instance should be. In this example, the servlet only needs the instance
to process an HTTP request; the instance can then be garbage collected.
This is specified using the javax.enterprise.context.RequestScoped
annotation:
@RequestScoped
public class MessageB implements Message { ... }