1. JNDI简介
1.1 定义
JNDI就是Sun提出的一套对象命名和目录服务的接口,全称为Java Naming and Directory Interface,简单的说就是JNDI通过目录服务的基础上抽象了一层来查找Java对象。引用维基百科中的定义如下:
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. Like all Java) APIs that interface with host systems, JNDI is independent of the underlying implementation. Additionally, it specifies a service provider interface (SPI) that allows directory service implementations to be plugged into the framework.[1] The information looked up via JNDI may be supplied by a server, a flat file, or a database; the choice is up to the implementation used.
根据他的定义,可以知道JNDI是通过SPI作为插件的方式应用于框架当中,通过JNDI查找的对象可以通过服务器,文件,或者数据库提供,这个是取决于具体的实现即可。
1.2 没有JNDI怎么办
在没有JNDI的时候,比如需要连接一个Mysql数据库,则需要通过硬编码的方式达到连接数据库的目的。如下代码所示,
Class.forName("com.mysql.jdbc.Driver",true,Thread.currentThread().getContextClassLoader());
Connection conn = DriverManager.getConnection("jdbc:mysql://test?user=landy&password=123456");
这样做的情况,就是等到需求改变的时候不容易修改,比如服务名称,数据库用户名密码等,甚者连接池参数等都可能修改。
1.3 JNDI使用场景
有了JNDI以后,程序员就只要关心自己的实现即可,不需要关注具体的数据库如何连接,如何配置用户名密码等操作。主要应用场景根据维基百科可以知道有以下几种:
Connecting a Java application to an external directory service (such as an address database or an LDAP server)
Allowing a Java Servlet to look up configuration information provided by the hosting web container.
总结起来就是两点,一点是连接数