Java Naming Directory Interface(JNDI,Java命名目录接口)。
JNDI允许程序通过一个名称来访问真正的Java对象,其包含了一些标准API接口,并且不依赖于任何独立的命名目录服务器。
JNDI API位于JDK的javax.naming包及其子包中。
使用JNDI至少需要提供3方面的支持:JNDI API、JNDI SPI、命名、目录服务器。
Lightweight Directory Access Protocol(JDAP)、Microsoft Active Directory都可实现与JNDI类似的功能。
命名服务:将名字和计算机系统内的一个对象建立关联,从而允许应用程序通过该名字来访问该对象。
目录服务:目录服务是对命名服务的扩展, 其不仅需要保存名称和对象之间的关联,而且还会保存对象的各种属性,以备开发者调用。
JNDI结构包含两组API:JNDI API和JNDI SPI(Service Provider Interface)。
功能:API允许开发者通过一致的方式来访问各种命名、目录服务,SPI保证各种命名、目录服务透明地加入JNDI结构中。(Naming Manager负责管理API和SPI之间的转换)
基本概念
binding:将一个名字绑定某个对象。
Context:一组绑定关系的集合,一个Context可有N个SubContext。
Naming System:遵循某种命名规则的绑定系统。如:文件系统。
Naming Service:对Naming System的扩展,允许通过名字来访问与之绑定的对象。
Directory Service:对Naming Service的扩展,其不仅需要保存名称和对象之间的关联,而且还会保存对象的各种属性,以备开发者调用。
访问绑定对象的步骤:
1:创建Context对象。
2:调用Context的lookup()方法根据JNDI名称来查找对象,或调用bind()、rebind()、unbind()来操作JNDI。
3:关闭Context对象。
如:
Context context = new InitialContext();
Object file = context.lookup(fileName);
context.close();
Context只是一个接口,通常使用它的实现类InitialContext来创建实例。InitialConext提供了的常用构造器:
InitialContext():读取系统属性来创建实例,常在服务器中使用。
InitialContext(Hashtable<?, ?> environment):需要提供属性,常在客户端中使用。
Hashtable至少包含以下key:
1:java.naming.factory.initial:可用Context.INITIAL_CONTEXT_FACTORY代替。(e.g. WebLogic提供了weblogic.jndi.WLInitialContextFactory, JBoss提供了org.jnp.interfaces.NamingContextFactory)
2:java.naming.provider.url:可用Context.PROVIDER_URL代替。(e.g. WebLogic提供了t3://localhost:7001,JBoss提供了localhost:1099)
public class Client {
public static void main(String[] args) throws Exception {
final String INIT_FACTORY = "weblogic.jndi.WLInitialContextFactory";
final String WL_URL = "t3://localhost:7001";
Hashtable properties = new Hashtable();
properties.put(Context.INITIAL_CONTEXT_FACTORY, INIT_FACTORY);
properties.put(Context.PROVIDER_URL, WL_URL);
Context context = new InitialContext(properties);
Object obj = context.lookup("fileName");
context.close();
}
}
WebSphere:
Context.INITIAL_CONTEXT_FACTORY
"com.ibm.websphere.naming.WsnInitialContextFactory "
Context.PROVIDER_URL
"iiop://localhost:900 "
Weblogic:
Context.INITIAL_CONTEXT_FACTORY
"weblogic.jndi.WLInitialContextFactory "
Context.PROVIDER_URL
"t3://127.0.0.1:7001 "
J2EE SDK(J2EE RI):
Context.INITIAL_CONTEXT_FACTORY
"com.sun.jndi.cosnaming.CNCtxFactory "
Context.PROVIDER_URL
"iiop://127.0.0.1:1050 "
SilverStream:
Context.INITIAL_CONTEXT_FACTORY
"com.sssw.rt.jndi.AgInitCtxFactory "
Context.PROVIDER_URL
"sssw://localhost:80 "
OC4J
Context.INITIAL_CONTEXT_FACTORY
"com.evermind.server.rmi.RMIInitialContextFactory"
Context.PROVIDER_URL
"ormi://127.0.0.1/"
JBOSS的:
java.naming.factory.initial
"org.jnp.interfaces.NamingContextFactory"
java.naming.provider.url
"localhost:1099"
WAS5:
Context.INITIAL_CONTEXT_FACTORY
"com.ibm.websphere.naming.WsnInitialContextFactory "
Context.PROVIDER_URL
"iiop://localhost:2809 "