Skip to main content

Resource injection in web applications

Posted by meeraj on December 15, 2005 at 2:35 AM PST

I have been looking at the Servlet 2.5 specification (Maintenance Review). One of the key additions is the ability to inject dependencies to classes whose lifecycle are maintained by the container.

The types of resources that can be injected in are generally the ones currently available for lookup from the java:comp/env namespace, by defining them in the deployment descriptor, as specified by the Servlet 2.4 specification. Resource injection relies on J2SE 5.0 annotaions. J2SE 5.0 is a pre-requirement for Servlet 2.5.

Injectable Classes

The classes that can be injected with external dependencies are,

  • Servlets
  • Filters
  • Various lifecycle and event listeners
  • Resource Types

    The annotaions available for dependency injection are

  • @Resource: This annotation is used to inject resource types that were broadly covered by resource-ref, resource-env-ref and message-destination-ref elements in the deployment descriptor. This will include datasources, JMS administered objects etc.
  • @Resources: This annotation acts as a container for multiple @Resource annotations.
  • @EJB: This annotaion provides the same functionality as ejb-ref and ejb-local-ref elements for injecting EJB references
  • @WebServiceRef: This annotation is used for injecting web service references.
  • @InjectionComplete: This is a method level annotation for the method to be called once all the dependencies are injected. For the ones familiar with Spring, this is similar to the afterPopertiesSet method on the InitializingBean interface.
  • Example

    The snippet below shows a simple example of injecting a datasource into a Servlet,

    public class MyServlet extends HttpServlet {
    @Resource(name="myDs") DataSource myDataSource;

    This injects a datasource by the JNDI name myDs into the field myDataSource. If the name attribute is not specified, the field name is treated as the JNDI name.


    Would you want the resource injection mechanism to be extended to ay classes load by the web application classloader, rather than only those classes whose lifecycle are managed by the container. Would the Servlet specification require EJB 3 persistence contexts to be injectable to web application classes?