CDI
January 12, 2019
CDI

References

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.

Resource Injection

Resource injection enables you to inject any resource available in the JNDI namespace into any container-managed object, such as a servlet, an enterprise bean, or a managed bean. For example, you can use resource injection to inject data sources, connectors, or custom resources available in the JNDI namespace.

For example, the following code injects a data source object that provides connections to the default Java DB database shipped with GlassFish Server:

1
2
3
4
5
public class MyServlet extends HttpServlet {
    @Resource(name="java:comp/DefaultDataSource")
    private javax.sql.DataSource dsc;
    ...
}