Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct JNDI @Resource(name)

Tags:

java

jboss

jndi

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

like image 800
Joe Avatar asked Mar 21 '13 12:03

Joe


People also ask

What is JNDI name in JBoss?

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.

What does JNDI lookup () Menthod do?

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.

What is Java comp env in JNDI?

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");

What is JNDI in Java with examples?

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.


1 Answers

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;
like image 63
Rodrigo Sasaki Avatar answered Oct 05 '22 22:10

Rodrigo Sasaki