简体   繁体   中英

Trouble using @Resource and JNDI lookup

I'm having trouble applying the concept of injection and also JNDI with EJBs and I'd like your help. I am learning this and I really want to understand and apply the techniques of @Resource and/or JNDI lookups with XML configuration. I can't seem to find any of the initial parameters in my JNDI lookups. Now, before I continue, if I manually enter the JNDI name of my datasource, everything works great. What I'm trying to do (again as an exercise) is use @Resource or JNDI to get the JNDI datasource name itself and then do a JNDI lookup on the datasource. I know that you can directly inject a DataSource object but if I can't inject a String, I gotta start with this.

First, here's the important part of my ejb-jar.xml:

<env-entry>
    <description>DataSource JNDI lookup name</description>
    <env-entry-name>datasourceName</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>myDataSource</env-entry-value>
</env-entry>

In terms of injection using @Resource I've tried I've tried the following field in the EJB

@Resource(name = "datasourceName")
String dsName;

I've also tried with mappedName and lookup (using JNDI lookup) nothing is coming in. Then I've tried JNDI lookup as follows:

 // get JNDI name from environment entry in EJB Context and use to lookup DataSource
Context context = new InitialContext();
String dsName = (String) context.lookup("java:comp/env/SRS/datasourceName");

(The name of the application is SRS) - This comes up with a NamingException that the JNDI lookup did not find anything. I've tried the following lookups:

String datasourceName = (String) context.lookup("java:comp/env/SRS/Status/datasourceName"); // name of EJB is Status
String datasourceName = (String) context.lookup("datasourceName");
String datasourceName = (String) context.lookup("SRS/datasourceName");           
String datasourceName = (String) context.lookup("SRS/Status/datasourceName");           
String datasourceName = (String) context.lookup("java:global/SRS/datasourceName");
String datasourceName = (String) context.lookup("java:global/SRS/Status/datasourceName");

My first post here so I hope I asked properly. Thanks for the help!

Ok. Two days later I saw that my mistake was nowhere in the code of the EJB itself but in a configuration of the JSP which invoked the EJB!! My mistake is that I had somehow invoked the methods of the EJB class as a POJO and NOT through the container. I had assumed since the EJB methods were being called that the container had correctly injected the EJB to the JSP. But it didn't. I put in a JNDI lookup in the JSP and everything resolved itself. Thanks everyone for your responses!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM