介绍

概述

Spring LDAP 旨在简化 Java 中的 LDAP 编程。该库提供的一些功能包括:spring-doc.cadn.net.cn

传统 Java LDAP 与LdapClient

考虑一种方法,该方法应该搜索所有人员的某个存储,并在列表中返回他们的姓名。 通过使用 JDBC,我们将创建一个连接,并使用一个语句运行一个查询。然后,我们将遍历结果集并检索我们想要的,将其添加到列表中。spring-doc.cadn.net.cn

使用 JNDI 处理 LDAP 数据库,我们将创建一个上下文并使用搜索过滤器执行搜索。然后,我们将遍历生成的命名枚举,检索我们想要的属性,并将其添加到列表中。spring-doc.cadn.net.cn

在 Java LDAP 中实现这种人名搜索方法的传统方法类似于下一个示例。请注意标记为粗体的代码 - 这是 实际执行与方法的业务目的相关的任务。剩下的就是管道了。spring-doc.cadn.net.cn

public class TraditionalPersonRepoImpl implements PersonRepo {
   public List<String> getAllPersonNames() {
      Hashtable env = new Hashtable();
      env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      env.put(Context.PROVIDER_URL, "ldap://localhost:389/dc=example,dc=com");

      DirContext ctx;
      try {
         ctx = new InitialDirContext(env);
      } catch (NamingException e) {
         throw new RuntimeException(e);
      }

      List<String> list = new LinkedList<String>();
      NamingEnumeration results = null;
      try {
         SearchControls controls = new SearchControls();
         controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
         results = ctx.search("", "(objectclass=person)", controls);

         while (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();
            Attribute attr = attributes.get("cn");
            String cn = attr.get().toString();
            list.add(cn);
         }
      } catch (NameNotFoundException e) {
         // The base context was not found.
         // Just clean up and exit.
      } catch (NamingException e) {
         throw new RuntimeException(e);
      } finally {
         if (results != null) {
            try {
               results.close();
            } catch (Exception e) {
               // Never mind this.
            }
         }
         if (ctx != null) {
            try {
               ctx.close();
            } catch (Exception e) {
               // Never mind this.
            }
         }
      }
      return list;
   }
}

通过使用 Spring LDAPAttributesMapperLdapClient类,我们可以通过以下代码获得完全相同的功能:spring-doc.cadn.net.cn

import static org.springframework.ldap.query.LdapQueryBuilder.query;

public class PersonRepoImpl implements PersonRepo {
   private LdapClient ldapClient;

   public void setLdapClient(LdapClient ldapClient) {
      this.ldapClient = ldapClient;
   }

   public List<String> getAllPersonNames() {
      return ldapClient.search().query(
            query().where("objectclass").is("person")
         ).toObject((Attributes attrs) ->
            attrs.get("cn").get().toString();
         );
   }
}

The amount of boilerplate code is significantly less than in the traditional example. The LdapClient search method makes sure a DirContext instance is created, performs the search, maps the attributes to a string by using the given AttributesMapper, collects the strings in an internal list, and, finally, returns the list. It also makes sure that the NamingEnumeration and DirContext are properly closed and takes care of any exceptions that might happen.spring-doc.cadn.net.cn

Naturally, this being a Spring Framework sub-project, we use Spring to configure our application, as follows:spring-doc.cadn.net.cn

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:ldap="http://www.springframework.org/schema/ldap"
       xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/ldap https://www.springframework.org/schema/ldap/spring-ldap.xsd">

   <ldap:context-source
          url="ldap://localhost:389"
          base="dc=example,dc=com"
          username="cn=Manager"
          password="secret" />

   <bean id="ldapClient" class="org.springframework.ldap.core.LdapClient" factory-method="create">
        <constructor-arg ref="contextSource" />
    </bean>

   <bean id="personRepo" class="com.example.repo.PersonRepoImpl">
      <property name="ldapClient" ref="ldapClient" />
   </bean>
</beans>
To use the custom XML namespace to configure the Spring LDAP components, you need to include references to this namespace in your XML declaration, as in the preceding example.

What’s new in 2.2

For complete details of 2.2, see the changelog for 2.2.0.RC1. The highlights of Spring LDAP 2.2 are as follows:spring-doc.cadn.net.cn

What’s new in 2.1

For complete details of 2.1, see the changelog for 2.1.0.RC1 and for 2.1.0 The highlights of Spring LDAP 2.1 are as follows.spring-doc.cadn.net.cn

What’s new in 2.0

While quite significant modernizations have been made to the Spring LDAP API in version 2.0, great care has been taken to ensure backward compatibility as far as possible. Code that works with Spring LDAP 1.3.x should, with few exceptions, compile and run when you use the 2.0 libraries without any modifications.spring-doc.cadn.net.cn

The exception is a small number of classes that have been moved to new packages in order to make a couple of important refactorings possible. The moved classes are typically not part of the intended public API, and the migration procedure should be smooth. Whenever a Spring LDAP class cannot be found after upgrade, you should organize the imports in your IDE.spring-doc.cadn.net.cn

You should expect to encounter some deprecation warnings, though, and there are also a lot of other API improvements. The recommendation for getting as much as possible out of the 2.0 version is to move away from the deprecated classes and methods and migrate to the new, improved API utilities.spring-doc.cadn.net.cn

The following list briefly describes the most important changes in Spring LDAP 2.0:spring-doc.cadn.net.cn

Packaging Overview

At a minimum, to use Spring LDAP you need the following:spring-doc.cadn.net.cn

In addition to the required dependencies, the following optional dependencies are required for certain functionality:spring-doc.cadn.net.cn

  • spring-data-ldap: Base infrastructure for repository support and so onspring-doc.cadn.net.cn

  • spring-context: Needed if your application is wired up by using the Spring Application Context. spring-context adds the ability for application objects to obtain resources by using a consistent API. It is definitely needed if you plan to use the BaseLdapPathBeanPostProcessor.spring-doc.cadn.net.cn

  • spring-tx: Needed if you plan to use the client-side compensating transaction support.spring-doc.cadn.net.cn

  • spring-jdbc: Needed if you plan to use the client-side compensating transaction support.spring-doc.cadn.net.cn

  • commons-pool: Needed if you plan to use the pooling functionality.spring-doc.cadn.net.cn

  • spring-batch: Needed if you plan to use the LDIF parsing functionality together with Spring Batch.spring-doc.cadn.net.cn

spring-data-ldap transitively adds spring-repository.xsd, which spring-ldap.xsd uses. Because of this, Spring LDAP’s XML config support requires the dependency even when Spring Data’s feature set is not in use.

Getting Started

The samples provide some useful examples of how to use Spring LDAP for common use cases.spring-doc.cadn.net.cn

Support

If you have questions, ask them on Stack Overflow with the spring-ldap tag. The project web page is spring.io/spring-ldap/.spring-doc.cadn.net.cn

Acknowledgements

The initial effort when starting the Spring LDAP project was sponsored by Jayway. Current maintenance of the project is funded by Pivotal, which has since been acquired by VMware.spring-doc.cadn.net.cn

Thanks to Structure101 for providing an open source license that has come in handy for keeping the project structure in check.spring-doc.cadn.net.cn