Resource injection in web applications
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,
Resource Types
The annotaions available for dependency injection are
resource-ref, resource-env-ref and message-destination-ref elements in the deployment descriptor. This will include datasources, JMS administered objects etc.ejb-ref and ejb-local-ref elements for injecting EJB referencesafterPopertiesSet 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.
Improvements?
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?
- Login or register to post comments
- Printer-friendly version
- meeraj's blog
- 1154 reads





