background image

The @Resource Annotation

<< Declaring Resource References | Duke's Bookstore Examples >>
<< Declaring Resource References | Duke's Bookstore Examples >>

The @Resource Annotation

TABLE 3­1
Web Components That Accept Resource Injections
Component
Interface/Class
Servlets
javax.servlet.Servlet
Servlet Filters
javax.servlet.ServletFilter
Event Listeners
javax.servlet.ServletContextListener
javax.servlet.ServletContextAttributeListener
javax.servlet.ServletRequestListener
javax.servlet.ServletRequestAttributeListener
javax.servlet.http.HttpSessionListener
javax.servlet.http.HttpSessionAttributeListener
javax.servlet.http.HttpSessionBindingListener
Taglib Listeners
Same as above
Taglib Tag Handlers
javax.servlet.jsp.tagext.JspTag
Managed Beans
Plain Old Java Objects
Declaring a Reference to a Resource
The @Resource annotation is used to declare a reference to a resource such as a data source, an
enterprise bean, or an environment entry. This annotation is equivalent to declaring a
resource-ref
element in the deployment descriptor.
The @Resource annotation is specified on a class, method or field. The container is responsible
for injecting references to resources declared by the @Resource annotation and mapping it to
the proper JNDI resources. In the following example, the @Resource annotation is used to inject
a data source into a component that needs to make a connection to the data source, as is done
when using JDBC technology to access a relational database:
@Resource javax.sql.DataSource catalogDS;
public getProductsByCategory() {
// get a connection and execute the query
Connection conn = catalogDS.getConnection();
..
}
The container injects this data source prior to the component being made available to the
application. The data source JNDI mapping is inferred from the field name catalogDS and the
type, javax.sql.DataSource.
If you have multiple resources that you need to inject into one component, you need to use the
@Resources
annotation to contain them, as shown by the following example:
Configuring Web Applications
Chapter 3 · Getting Started with Web Applications
95