简体   繁体   中英

Correct JNDI @Resource(name)

I have the following class for obtaining a JDBC connection:

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 @Resource annotation. 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).

I have tried:

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

@Resource(name="oracleDS")

AS is JBOSS AS7

What name did you define in your standalone.xml ?

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

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

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

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

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