Home

 

Dependency injection

The new specification introduces a powerful mechanism for obtaining Java EE resources (JDBC data source, JMS factories and queues, EJB references) and to inject them into EJBs, entities, or EJB clients.

In EJB 2.x, the only way to obtain these resources was to use JNDI lookup using resource references. This method required a piece of code that could become cumbersome and vendor specific, because very often you had to specify properties related to the specific J2EE container provider.

EJB 3.0 adopts a dependency injection (DI) pattern, which is one of the best ways to implement loosely coupled applications. It is much easier to use and more elegant than older approaches, such as dependency lookup through JNDI or container callbacks.

The implementation of dependency injection in the EJB 3.0 specification is based on annotations or XML descriptor entries, which allow you to inject dependencies on fields or setter methods.

Instead of complicated XML EJB references or resource references, you can use the @EJB and @Resource annotations to set the value of a field or to call a setter method within your beans with anything registered within JNDI. With these annotations, you can inject EJB references and resource references such as data sources and JMS factories.

In this section we show the most common usage of dependency injection in EJB 3.0.

ibm.com/redbooks