Search code examples
javawebspherejndijava-ee-6

WebSphere <env-entry> in application.xml and @Resource injection


I can't inject environment entries from application.xml using the @Resource annotation in my WebSphere 8.5.5 application. (I don't want to move the entry down to the component level ejb-jar.xml.) What am I missing?

application.xml:

<application
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_6.xsd"
        version="6">

    <env-entry>
        <env-entry-name>fileName</env-entry-name>
        <env-entry-type>java.lang.String</env-entry-type>
        <env-entry-value>theValue</env-entry-value>
    </env-entry>

With this, I do see "fileName" defined as "theValue" in the WebSphere Admin Console section Environment entries for the application. Yet I can't figure out how to access this from my EJB.

StartupBean.java:

@Singleton
@Startup
public class StartupBean {
    @Resource(name = "fileName")
    private String fileName = "default";

fileName is always "default", not "theValue".

I tried a manual lookup using both "java:comp" and "java:app" (as suggested by this thread), but both throw NamingException

Context ctx = new InitialContext();
fileName = (String) ctx.lookup("java:comp/env/fileName");
fileName = (String) ctx.lookup("java:app/env/fileName");

Solution

  • Resources declared in application.xml must use either the java:app/env or java:global/env prefix, so it should look like:

    <env-entry>
        <env-entry-name>java:app/env/fileName</env-entry-name>
        <env-entry-type>java.lang.String</env-entry-type>
        <env-entry-value>theValue</env-entry-value>
    </env-entry>
    

    Then, injection into the field would be as follows:

    @Resource(name = "java:app/env/fileName")
    private String fileName = "default";