Java JNDIUtil-class And Method Code Example


Here is an example of how the JNDIUtil class from the logback library can be used:

import ch.qos.logback.core.util.JNDIUtil;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class MyClass {
    public static void main(String[] args) {
        try {
            InitialContext initialContext = new InitialContext();
            JNDIUtil.bind("java:comp/env/jdbc/mydatasource", initialContext, "jdbc:mysql://localhost:3306/mydb");
            String dataSourceUrl = (String) JNDIUtil.lookup("java:comp/env/jdbc/mydatasource", initialContext);
            System.out.println("Data source URL: " + dataSourceUrl);
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }
}

In this example, MyClass uses an instance of JNDIUtil to bind a JDBC data source URL to a JNDI name and then look up the data source URL using that JNDI name. The bind method takes three arguments: the JNDI name to bind, an instance of the InitialContext class, and the object to bind (in this case, the JDBC data source URL). The lookup method takes two arguments: the JNDI name to look up and an instance of the InitialContext class.

You can also use unbind method to unbind object from JNDI.

JNDIUtil.unbind("java:comp/env/jdbc/mydatasource", initialContext);

This will unbind the object bound to "java:comp/env/jdbc/mydatasource" JNDI name.

Please note that this example uses JNDI to bind and look up a JDBC data source URL, but JNDI can be used to bind and look up other types of objects as well.