Using Predefined Beans in CDI Applications (original) (raw)

Java EE provides predefined beans that implement the following interfaces.

To inject a predefined bean, create an injection point to obtain an instance of the bean by using the javax.annotation.Resource annotation for resources or the javax.inject.Inject annotation for CDI beans. For the bean type, specify the class name of the interface the bean implements.

Table 27-1 Injection of Predefined Beans

Predefined Bean Resource or CDI Bean Injection Example
UserTransaction Resource @Resource UserTransaction transaction;
Principal Resource @Resource Principal principal;
Validator Resource @Resource Validator validator;
ValidatorFactory Resource @Resource ValidatorFactory factory;
HttpServletRequest CDI bean @Inject HttpServletRequest req;
HttpSession CDI bean @Inject HttpSession session;
ServletContext CDI bean @Inject ServletContext context;

Predefined beans are injected with dependent scope and the predefined default qualifier @Default.

The following code snippet shows how to use the @Resource and@Inject annotations to inject predefined beans. This code snippet injects a user transaction and a context object into the servlet classTransactionServlet. The user transaction is an instance of the predefined bean that implements the javax.transaction.UserTransactioninterface. The context object is an instance of the predefined bean that implements the javax.servlet.ServletContext interface.

import javax.annotation.Resource;
import javax.inject.Inject;
import javax.servlet.http.HttpServlet;
import javax.transaction.UserTransaction;
...
public class TransactionServlet extends HttpServlet {
    @Resource UserTransaction transaction;
    @Inject ServletContext context;
    ...
}