java 正确的 JNDI @Resource(name)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15547986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:01:05  来源:igfitidea点击:

Correct JNDI @Resource(name)

javajbossjndi

提问by Joe

I have the following class for obtaining a JDBC connection:

我有以下用于获取 JDBC 连接的类:

package util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class OracleConnection implements AutoCloseable{

private final String oracle_DS_CTX = "java:jboss/oracleDS"; 

    //  @Resource(name="java:jboss/oracleDS")
    //  private DataSource ds; //doesn't work   

    private Connection _conn;   

    public OracleConnection() throws SQLException, NamingException{

            Context ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup(oracle_DS_CTX);
            _conn = ds.getConnection();
    }

    @Override
    public void close() throws Exception {
            if(_conn != null){
                    _conn.close();
            }
    }

    public Connection getConnection() throws SQLException {
            return _conn;
    }
}    

I have a problem using the @Resourceannotation. Datasource obtained via InitialContext works without any problems but I am not sure what string should I put into resource name (commented out in my code).

我在使用@Resource注释时遇到问题。通过 InitialContext 获得的数据源工作没有任何问题,但我不确定应该将什么字符串放入资源名称(在我的代码中注释掉)。

I have tried:

我努力了:

@Resource(name="java:jboss/oracleDS")

@Resource(name="java:jboss/oracleDS")

@Resource(name="oracleDS")

@Resource(name="oracleDS")

AS is JBOSS AS7

AS是JBOSS AS7

回答by Rodrigo Sasaki

What name did you define in your standalone.xml?

你在你的standalone.xml 中定义了什么名字?

That is the name you need to define in your @Resource

那是您需要在您的 @Resource

But there's a little trick, you need to set it in the lookupproperty instead of name.

但是有一个小技巧,您需要在lookup属性而不是name 中设置它。

Here's an example, let's assume my DS jndi is java:jboss/ExampleDS.

这是一个例子,让我们假设我的 DS jndi 是java:jboss/ExampleDS.

@Resource(lookup = "java:jboss/ExampleDS")
private DataSource dataSource;