---
title: "SpringLDAP-Reference（中文文档）(一)"
author: "xrb2008"
date: "2010-04-14T17:03:09Z"
tags: ["Bean", "DAO", "JDBC", "Spring", "编程"]
categories: ["企业架构"]
slug: "springldap-reference"
draft: false
lastmod: "2010-04-14T17:03:09Z"
id: 643881
url: "https://xrb2008.iteye.com/blog/643881"
---

**序言**

      Ldap jndi类似于sql编程用jdbc访问数据库，JDBC和JAVA LDAP之间有若干个相同点，虽然是两种完全不同的利弊权衡不同的API，但它们有着一些共有的特性

  \*即使是最简单的任务，它们都需要大量的底层命令来处理  
  \*不管发生什么情况，程序必须要正确的关闭  
  \*异常处理困难  
    
       以上的几点情况导致了APIS的普通使用中存在着大量的重复代码，正如我们都知道，重复代码是最严重的一个问题。总之，归结为java程序中的jdbc和ldap都难以置信地重复和落后。

      SpringJDBC是spring框架的一部分，它提供了简明的SQL程序接口，对于JAVA LDAP程序，我们需要一个与之类似的框架。

 

    
第一章 介绍

1.1概述

 SpringLDAP是一个简单的LDAP的Java编程库，建立在作为JdbcTemplate的SpringJDBC同样的原则，它完全无需担心创建和关闭LdapContext和NamingEnumeration遍历，它还提供了一个更为全面的未经检查的异常层次结构，建立在Spring的 DataAccessException 基础上， 附带的，它还提供了对属性的LDAP动态过滤器和DNS(DistinguishedNames)，LDAP属性管理，客户端的LDAP事务管理。  
 设想，一个案例，一个方法要将一些person的属性搜索出来并存储在一个列表中返回，如果使用JDBC，我们需要建立一个连接，执行查询语句。我们将循环结果集并检索我们需要的属性，将它放在一个列表中。相比之下，使用JAVA LDAP ，我们将建立一个上下文（CONTEXT）使用搜索过滤器执行搜索，循环结果集，检索我们需要的属性放在一个列表中。  
   
 JAVA LDAP 对一个人的姓名查询的传统方式看起来像这样，具体执行方法为粗体部分。（代码间没空格，比较乱，建议对照英文文档）  
 packagecom.example.dao;  
publicclassTraditionalPersonDaoImplimplementsPersonDao{  
publicListgetAllPersonNames(){  
Hashtableenv=newHashtable();  
env.put(Context.INITIAL\_CONTEXT\_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");  
env.put(Context.PROVIDER\_URL,"[ldap://localhost:389/dc=example,dc=com]()");  
DirContextctx;  
try{  
ctx=newInitialDirContext(env);  
}catch(NamingExceptione){  
thrownewRuntimeException(e);  
}  
LinkedListlist=newLinkedList();  
NamingEnumerationresults=null;  
try{  
SearchControlscontrols=newSearchControls();  
controls.setSearchScope(SearchControls.SUBTREE\_SCOPE);  
**results=ctx.search("","(objectclass=person)",controls);**  
while(results.hasMore()){  
SearchResultsearchResult=(SearchResult)results.next();  
Attributesattributes=searchResult.getAttributes();  
**Attributeattr=attributes.get("cn");**  
**Stringcn=(String)attr.get();**  
**list.add(cn);**  
}  
}catch(NameNotFoundExceptione){  
//Thebasecontextwasnotfound.  
//Justcleanupandexit.  
}catch(NamingExceptione){  
thrownewRuntimeException(e);  
}finally{  
if(results!=null){  
try{  
results.close();  
}catch(Exceptione){  
//Nevermindthis.  
}  
}  
if(ctx!=null){  
try{  
ctx.close();

}catch(Exceptione){  
//Nevermindthis.  
}  
}  
}  
returnlist;  
}  
}

 

使用spring ldap的AttributesMapper和 LdapTemplate，我们可以用下列代码实现相同的功能

packagecom.example.dao;  
publicclassPersonDaoImplimplementsPersonDao{  
privateLdapTemplateldapTemplate;  
publicvoidsetLdapTemplate(LdapTemplateldapTemplate){  
this.ldapTemplate=ldapTemplate;  
}  
publicListgetAllPersonNames(){  
returnldapTemplate.search(  
"","(objectclass=person)",  
newAttributesMapper(){  
publicObjectmapFromAttributes(Attributesattrs)  
throwsNamingException{  
returnattrs.get("cn").get();  
}  
});  
}  
}

以上代码明显比传统方式更加节省了代码数量，LdapTemplate的搜索方法执行搜索，将属性信息放在一个字符串中放在AttributesMapper中，然后将它放在集合中返回。  
需要注意的是，这个PersonDaoImpl代码只是一个特定的简单实例，而不能用于任何地方，为此，Sping Ldap提供了一个set方法，There is nothing Spring-specific about this"Inversion of Control"，  
任何人都可以创建一个PersonDaoImpl实例，并注入LdapTemplate.不管如何，Spring提供了一个简便容易的方法实现了它，Spring容器可以告诉一个实例与LdapTemplate的依赖关系，并将它注入到PersonDao实例中。定义方式有很多种，通常采用XML方式

&lt;beans&gt;  
&lt;beanid="contextSource"class="org.springframework.ldap.core.support.LdapContextSource"&gt;  
&lt;propertyname="url"value="[ldap://localhost:389"/]()&gt;  
&lt;propertyname="base"value="dc=example,dc=com"/&gt;  
&lt;propertyname="userDn"value="cn=Manager"/&gt;  
&lt;propertyname="password"value="secret"/&gt;  
&lt;/bean&gt;  
&lt;beanid="ldapTemplate"class="org.springframework.ldap.core.LdapTemplate"&gt;  
&lt;constructor-argref="contextSource"/&gt;  
&lt;/bean&gt;  
&lt;beanid="personDao"class="com.example.dao.PersonDaoImpl"&gt;  
&lt;propertyname="ldapTemplate"ref="ldapTemplate"/&gt;  
&lt;/bean&gt;  
&lt;/beans&gt;

1.2包概述

至少，使用Spring Ldap你需要：  
? spring-ldap-core (the SpringLDAP library)  
? spring-core (内部公用类)  
? spring-beans (操作Java Bean接口)  
? commons-logging (a simple logging facade,used internally)  
? commons-lang (misc utilities,used internally)

除了以上这些包，你还可能需要以下这些：  
? spring-context (如果你要使用Spring上下文，采用一致的API增加对资源获取的能力，如果你有必要对BaseLdapPathBeanPostProcessor规划使用.)  
? spring-tx (如果你需要使用客户端的补偿事务（compensating transaction）支持）  
? spring-jdbc (如果你需要操作数据库)  
? ldapbp (Sun Ldap增强包--如果你要使用Ldap V3标准且你没使用JAVA5或更高版本)  
? commons-pool (如果你需要使用连接池功能)

1.3 包结构  
本节提供了一个Spring Ldap包逻辑结构的示意图，包之间的依赖关系已经注明

（图插不上来，对照英文文档）  
1.3.1.org.springframework.transaction.compensating  
该包提供了通用的事务支持，这不同于LDAP-specific or JNDI-specific  
\*依赖关系:commons-logging

1.3.2.org.springframework.ldap  
该包提供了异常处理库，这种uncheck层次的异常反映了NamingException的层次。  
\*依赖关系:spring-core

1.3.3.org.springframework.ldap.core  
该包包含了开发的核心接口，这些接口包括AuthenticationSource,ContextSource,DirContextProcessor,和NameClassPairCallbackHandler，而且包含了class LdapTemplate核心，加上各种映射及执行代码  
\*依赖关系:ldap,ldap.support,spring-beans,spring-core,spring-tx,commons-lang,commons-logging

1.3.4.org.springframework.ldap.core.support  
该包提供了接口实现的核心部分  
\*依赖关系:ldap,ldap.core,ldap.support,spring-core,spring-beans,spring-context,commons-lang,commons-logging

1.3.5.org.springframework.ldap.core.simple  
该包提供了部分Spring LDAP的Java5特性，主要是使用java的泛型简化开发，得到更好的context容器，更好的查询和操作方法。  
?依赖关系:ldap.core

1.3.6.org.springframework.ldap.pool  
该包提供了在per-ContextSource基础上的连接池配置支持。池操作支持通过PoolingContextSource包装ContextSource和池只读和读写DirContext对象。JakartaCommons-Pool提供最基本的池实现  
?依赖关系：ldap.core,commons-lang,commons-pool

1.3.7.org.springframework.ldap.pool.factory  
该包提供了实际池连接函数和其它创建连接函数  
?依赖关系：ldap,ldap.core,ldap.pool,spring-beans,spring-txcommons-lang,commons-logging,commons-pool

1.3.8.org.springframework.ldap.pool.validation  
该包提供了对池连接的验证支持  
?依赖关系:ldap.pool,commons-lang,commons-logging

1.3.9.org.springframework.ldap.support  
该包提供一些辅助工具函数，如异常转换等  
?依赖关系:ldap,spring-core,commons-logging

1.3.10.org.springframework.ldap.authentication  
该包包含了一个AuthenticationSource接口的实现，即使在没有登录的情况下，也可以用它来查询一些信息  
?依赖关系:ldap.core,spring-beans,commons-lang

1.3.11.org.springframework.ldap.control  
该包包含了一个DirContextProcessor的抽象接口，用来做请求控制。还有一个具体搜索分页及排序。除非使用JAVA5，LDAP Booster Pack才可以用来获得请求和控制  
?依赖关系:ldap,ldap.core,LDAPboosterpack(optional),spring-core,commons-lang,  
commons-logging

1.3.12.org.springframework.ldap.filter  
该包提供过滤器库及一些实现  
?依赖关系:ldap.core,spring-core,commons-lang

1.3.13.org.springframework.ldap.transaction.compensating  
该包提供了一些LDAP-specific的核心事务实现  
?依赖关系:ldap.core,transaction.compensating,spring-core,commons-lang,commons-logging

1.3.14.org.springframework.ldap.transaction.compensating.manager  
该包提供了一些客户端的核心事务实现  
?依赖关系:ldap,ldap.core,ldap.support,ldap.transaction.compensating,transaction.compensating,  
spring-tx,spring-jdbc,spring-orm,commons-logging

1.3.15.org.springframework.ldap.transaction.compensating.support  
该包提供了一些有用客户端的核心事务实现的其它函数  
?依赖关系:ldap.core,ldap.transaction.compensating

具体的JAR包请从源代码包中获得

Spring Ldap支持Spring 2.0及以上版本  
社区支持论坛：[http://forum.springframework.org](http://forum.springframework.org)  
项目主页：[http://www.springframework.org/ldap](http://www.springframework.org/ldap)