10/08/2007

Type-level injection in JavaEE

There are 3 types of resource injections in JavaEE: field injection, setter injection, and type-level injection, in the order of usage frequency.

Unlike field and setter injections, type-level injections are not really injection. It does not inject anything into anywhere; it just declares a resource reference in a descriptor-free manner.

To use resource injected at type-level, you will need to do a traditional JNDI lookup. What we have saved here, compared to pre-JavaEE-5, is there is no need for deployment descriptors.

A servlet example in glassfish:

@Resource(type=javax.sql.DataSource.class, 
name="jdbc/defaultDataSource,
mappedName="jdbc/__default")

public class FooServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
//This is how to use the resource injected at type-level
Connection con = null;
try {
InitialContext ic = new InitialContext();
DataSource ds =
(DataSource) ic.lookup("java:comp/env/jdbc/defaultDataSource");
con = ds.getConnection();
} catch (NamingException ex) {
throw new ServletException(ex);
} catch (SQLException ex) {
throw new ServletException(ex);
} finally {
//close connection here
}
}
Type-level injections are inherently verbose, compared to field and setter injections, where a bare @EJB or @Resource is sufficient in some cases. Field and setter injections can use the field type and parameter type to infer the resource type, respectively. Type-level injections can't. All the necessary attributes must be present.

For @Resource, you must specify at least name and type. For @EJB, you must have at least beanInterface and name.