简体   繁体   English

带有资源注释的 JNDI 查找总是 NULL

[英]JNDI Lookup with Resource annotation always NULL

I've got a WebApp with Tomcat 10, Java11 using Jersey3.我有一个使用 Jersey3 的 Tomcat 10、Java11 的 WebApp。 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.我在上下文中定义了一个 ConnectionPool。xml 用于处理与我的 OracleDB 的连接,现在我试图通过@Resource注释访问我的context.xml中的数据源。 This should invoke a JNDI-lookup.这应该调用 JNDI 查找。 Unfortunately, I always get a NPE as it seems not to find the resource while running... What am I doing wrong?不幸的是,我总是得到一个 NPE,因为它似乎在运行时找不到资源......我做错了什么? 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.根据教程,当我直接在 context.xml 中定义资源时,引用链接是可选的。

Thanks for any input!感谢您的任何意见!

This link is about jboss, but would seem relevant to you too. 此链接是关于 jboss,但似乎也与您相关。 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.它说,根据规范,进行 JNDI 查找的资源注释仅适用于 EJB,因此不适用于您的情况。

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.如果你能找到你的数据源,你可以尝试优化以避免上面的“手动”查找。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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