Aleydin Karaimin
Aleydin Karaimin

Reputation: 964

JNDI reference and lookup resource without web.xml

My application has an external dependency where resource class is defined - e.g com.sample.SomeResource. The application server where my application runs on, provide environment resources which I can use in my application. One of them is an instance of com.sample.SomeResource. If my app has web descriptor - web.xml I can use <resource-ref> tag to reference it:

<resource-ref>
        <res-ref-name>SomeResource</res-ref-name>
        <res-type>com.sample.SomeResource</res-type>
    </resource-ref>

and then I can lookup for it.

 try {
      InitialContext initialContext = new InitialContext();
      SomeResource someResource= (SomeResource) ctx.lookup("java:comp/env/SomeResource");
    } catch (NamingException e) {
      ...
    }

However, I want to get rid of the web.xml. Is there a way to define it programmatically (dynamically)?

Upvotes: 2

Views: 1650

Answers (1)

mahsum
mahsum

Reputation: 350

you can use javax.annotation.Resource annotation on a field.

@Resource(lookup = "java:comp/env/SomeResource")
 private SomeResource someResource;

Upvotes: 1

Related Questions