JNDI

JNDI

Java Naming And Directory Interface
从名字可看出,它包含命名和目录接口。涉及的概念如下:

Names

Name是对象的结识,名字由组件、分隔符组成。在一个Naming System中,通过Name去查找对象。下面为三种常用命名系统的命名规则。

Naming SystemComponent SeparatorNames
UNIX file system "/" /usr/hello
DNS "." sales.Wiz.COM
LDAP "," and "=" cn=Rosanna Lee, o=Sun, c=US

Bindings

把名字和对象关联起来叫绑定。例如,一个文件名关联到一个文件。

Context

一组绑定就叫上下文, 它提供查找对象、绑定、解绑以及列出所有绑定等功能。Context可以包含SubContext。

Naming System

命名系统把一系列Context(具有相同 合名规则)关联起来,并且提供公共操作。
命名系统提供Namig service完成命名相关操作。Naming Service又是通过Name Interfac去获取。

Directory Service

许多Naming Service会通过Directory Service扩展,目录服务把names、attributes与对象关联。

directory service = naming service + objects containing attributes

除了可以通过名字查找对象,也可以通过属性查找对象。

如电话公司的目录服务,它把用户与它的地址和电话号码关联。

directory is a connected set of directory objects. A directory service is a service that provides operations for creating, adding, removing, and modifying the attributes associated with objects in a directory. The service is accessed through its own interface.

常用的目录服务有

Network Information Service (NIS)

Oracle Directory Server

Search Service

目录服务除了可以根据名字查找,还可以根据逻辑表达式查找。

例如,可以这样查询目录服务:

  • all users that have the attribute "age" greater than 40 years.
  • all machines whose IP address starts with "192.113.50".

 

JNDI

The Java Naming and Directory Interface™ (JNDI) is an application programming interface (API) that provides naming and directory functionality to applications written using the Java™ programming language. 

Architecture

Packaging

JNDI is included in the Java SE Platform. To use the JNDI, you must have the JNDI classes and one or more service providers. The JDK includes service providers for the following naming/directory services:

  • Lightweight Directory Access Protocol (LDAP)
  • Common Object Request Broker Architecture (CORBA) Common Object Services (COS) name service
  • Java Remote Method Invocation (RMI) Registry
  • Domain Name Service (DNS)

Coding分析

Context envContext = (Context)initContext.lookup("java:comp/env"); 

(DataSource)envContext.lookup("jdbc/MyDatasource");

java:comp/env有啥用?

java在这表示一种url scheme, comp代表component。JNDI会调用javaURLContextFactory,它通常由app空中提供,比如由tomcat实现。

it's a root namespace provided by the container for you to look up your resources in.

it's the node in the JNDI tree where you can find properties for the current Java EE component.

 

参考资料:

http://docs.oracle.com/javase/tutorial/jndi/concepts/index.html

http://docs.oracle.com/javase/tutorial/jndi/concepts/directory.html

http://www.codejava.net/servers/tomcat/configuring-jndi-datasource-for-database-connection-pooling-in-tomcat

 

posted @ 2016-03-14 10:21  Season2009  阅读(180)  评论(0编辑  收藏  举报