How to ensure JNDI resources are available for application during startup/shutdown of JBoss EAP 7 / 6
Environment
- Red Hat JBoss Enterprise Application Platform (EAP)
- 7.x
- 6.x
Issue
-
An web application uses a
javax.servlet.ServletContextListenerto catch thecontextDestroyedevent and needs to access to a database. Attempts to obtain theDataSourcefrom JNDI during this process receive ajavax.naming.NameNotFoundExceptionindicating that the JNDI repository does not contain theDataSource. -
Is it possible to configure the datasource such that when the JBoss is shut down, then, first the application is disabled/undeployed and then the DataSource will be shutdown?
-
How do I ensure a resource in JNDI is available during startup or shutdown of an application?
-
I have a HA singleton service(cluster wide) that initializes an ejb timer. To initialize the timer, I am doing a jndi look up of the ejb from HA service. This look up is randomly failing with 'Caused by: javax.naming.NameNotFoundException.
Resolution
JBoss EAP needs to know about the dependency to make sure it is available to the application.
If the resource is injected with @Resource, a dependency is automatically set up.
@Resource (lookup="java:jboss/datasources/MyDataSource")
private DataSource datasource;
Otherwise use a <resource-ref> tag in the application descriptor (web.xml for web applications, ejb-jar.xml for EJBs, etc.) to tie the resource's global JNDI name to the web app's local ENC, and then use @Resource injection or the the Naming API to look it up using the local name. This also sets up a dependency.
<resource-ref>
<res-ref-name>MyDataSource</res-ref-name>
<jndi-name>java:jboss/datasources/MyDataSource</jndi-name>
</resource-ref>
Root Cause
When using manual JNDI lookups, there is no explicit dependency between the application and resources in JNDI such as datasources.
If JBoss EAP does not know about the dependency, it cannot make sure it is available during startup or shutdown.
This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.