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
The JBoss naming service is an implementation of the Java Naming and Directory Interface (JNDI). JNDI plays a key role in J2EE because it provides a naming service that allows a user to map a name onto an object.
The Java Naming and Directory Interface (JNDI) is a Java API for a directory service that allows Java software clients to discover and look up data and resources (in the form of Java objects) via a name.
java:comp/env is the node in the JNDI tree where you can find properties for the current Java EE component (a webapp, or an EJB). Context envContext = (Context)initContext.lookup("java:comp/env");
JNDI is an API used to access the directory and naming services (i.e. the means by which names are associated with objects). The association of a name with an object is called a binding. A basic example of a naming service is DNS which maps machine names to IP addresses.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With