Registering DataSource with JNDI


Registering DataSource with JNDI

In this tutorial you will learn how register a JDBC DataSource with JNDI

In this tutorial you will learn how register a JDBC DataSource with JNDI

Registering The DataSource With JNDI

Java Naming Directory Interface (JNDI)

Java Naming Directory Interface (JNDI) is an API of java technology which provides naming and directory functionality to java applications. It is designed using Java Object Model for java applications. With the name of JNDI java application can store and retrieve named java object of any type. It provides methods for performing standard directory operation, for example searching for objects for their associating attributes etc.

An Example of DataSource registration with JNDI is given below

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.ConnectionPoolDataSource;

import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

public class RegisteringJNDIWithDataSource {
	private static void startRegistry() throws RemoteException {
		System.out.println("RMI registry Stared.");

	private static InitialContext createInitialContextContext()
			throws NamingException {
		Properties properties = new Properties();
		properties.put(Context.PROVIDER_URL, "rmi://localhost:1059");
		InitialContext initialContextcontext = new InitialContext(properties);
		return initialContextcontext;

	public static void main(String args[]) {
		try {
			ConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
			((MysqlDataSource) dataSource).setUser("root");
			((MysqlDataSource) dataSource).setPassword("root");
			((MysqlDataSource) dataSource).setServerName("");
			((MysqlDataSource) dataSource).setPort(3306);
			((MysqlDataSource) dataSource).setDatabaseName("student");

			InitialContext context = createInitialContextContext();
			context.rebind("Source", dataSource);

		} catch (Exception e) {
When you run this application it will display message as shown below:

RegistryImpl_Stub[UnicastRef [liveRef: [endpoint:[](remote),objID:[0:0:0, 0]]]]
RMI registry Stared.

Download this example code