Default JNDI Name for Resource or EJB Injection

When a resource or EJB reference is injected to a component class, not only can you directly use this variable, you can also lookup with JNDI. For example,
package demo;
public class FooServlet extends HttpServlet {
@Resource(name="jdbc/mysql-ds")
private DataSource dataSource;

protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Connection con = null;
Connection conn = null;
try {
InitialContext ic = new InitialContext();
DataSource ds =
(DataSource) ic.lookup("java:comp/env/jdbc/mysql-ds");

//the following 2 statements work the same:
conn = dataSource.getConnection();
con = ds.getConnection();
} catch (NamingException ex) {
throw new ServletException(ex);
} catch (SQLException ex) {
throw new ServletException(ex);
} finally {
//close con conn here
}
}
}
If the name() field is not specified for @EJB or @Resource, the default jndi name is not the variable name; instead, it's in the form of fully-qualified-classname/variable-name. Therefore, using default jndi name, the above example needs to be rewrite as follows:
package demo;
public class FooServlet extends HttpServlet {
@Resource
private DataSource dataSource;

protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Connection con = null;
Connection conn = null;
try {
InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup(
"java:comp/env/demo.FooServlet/dataSource");

//the following 2 statements work the same:
conn = dataSource.getConnection();
con = ds.getConnection();
} catch (NamingException ex) {
throw new ServletException(ex);
} catch (SQLException ex) {
throw new ServletException(ex);
} finally {
//close con conn here
}
}
}

Followers

Pageviews Last 7 Days