简体   繁体   中英

JNDI Lookup with Resource annotation always NULL

I've got a WebApp with Tomcat 10, Java11 using Jersey3. I defined a ConnectionPool in my context.xml for handling the connection to my OracleDB and now I'm trying to access the DataSource within my controller through a @Resource annotation. This should invoke a JNDI-lookup. Unfortunately, I always get a NPE as it seems not to find the resource while running... What am I doing wrong? Or what would the correct mappedName / lookup be?

  @Path("/data")
public class DataController  {

    @Context
    ServletContext context;

    @Resource(lookup = "java:/jdbc/myDB") //also tried java:/comp/env/jdbc/myDB and mappedName="jdbc/myDB"
    protected DataSource ds; //always null
<Context name="myapp">
<Resource type="javax.sql.DataSource"
          name="jdbc/myDB"
          factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
          driverClassName="oracle.jdbc.OracleDriver"
          url="jdbc:oracle:thin:@//localhost:1521/orcl"
          username="xy"
          password="xy"/>

According to the tutorials, a ref-link is optional when I define the resource directly in the context.xml.

Thanks for any input!

This link is about jboss, but would seem relevant to you too. It says that according to the specification, Resource annotation to do JNDI lookups would only work with EJBs, so it wouldn't work for your case.

A workaround is to do the programmatic way to see if your datasource is working:

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource bean = (DataSource ) envCtx.lookup("jdbc/myDB");

If you can find your datasource you can then try to optimize to avoid "manual" lookup above.

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