簡介

概述

Spring LDAP 旨在簡化 Java 中的 LDAP 程式設計。該庫提供的一些功能包括:

  • 類似於 JdbcTemplate 的模板簡化 LDAP 程式設計。

  • JPA 或 Hibernate 風格的基於註解的物件與目錄對映。

  • Spring Data 倉庫支援,包括 QueryDSL 支援。

  • 簡化 LDAP 查詢和可分辨名稱構建的實用工具。

  • 適當的 LDAP 連線池。

  • 客戶端 LDAP 補償事務支援。

傳統 Java LDAP 與 LdapClient

考慮一個方法,它應該搜尋某個儲存中的所有人員並返回他們的姓名列表。使用 JDBC,我們將建立一個連線,並使用一個語句執行一個查詢。然後,我們將遍歷結果集並檢索我們想要的,將其新增到列表中。

使用 JNDI 對 LDAP 資料庫進行操作,我們將建立一個上下文並使用搜尋過濾器執行搜尋。然後,我們將遍歷生成的命名列舉,檢索我們想要的屬性,並將其新增到列表中。

在 Java LDAP 中實現此人名搜尋方法的傳統方式如下例所示。請注意粗體標記的程式碼——這是實際執行與該方法的業務目的相關的任務的程式碼。其餘部分是管道。

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://: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 LDAP 的 AttributesMapperLdapClient 類,我們透過以下程式碼獲得完全相同的功能:

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();
         );
   }
}

樣板程式碼的數量明顯少於傳統示例。LdapClient 搜尋方法確保建立 DirContext 例項,執行搜尋,使用給定的 AttributesMapper 將屬性對映為字串,將字串收集到內部列表中,最後返回列表。它還確保 NamingEnumerationDirContext 正確關閉,並處理可能發生的任何異常。

當然,作為 Spring Framework 的子專案,我們使用 Spring 配置我們的應用程式,如下所示:

<?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://: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>
要使用自定義 XML 名稱空間配置 Spring LDAP 元件,您需要在 XML 宣告中包含對此名稱空間的引用,如上例所示。

2.2 版本的新特性

有關 2.2 的完整詳細資訊,請參閱 2.2.0.RC1 的變更日誌。Spring LDAP 2.2 的亮點如下:

  • #415:增加了對 Spring 5 的支援

  • #399:嵌入式 UnboundID LDAP 伺服器支援

  • #410:增加了 Commons Pool 2 支援的文件

2.1 版本的新特性

有關 2.1 的完整詳細資訊,請參閱 2.1.0.RC12.1.0 的變更日誌。Spring LDAP 2.1 的亮點如下。

  • #390:增加了 Spring Data Hopper 支援

  • #351:增加了對 commons-pool2 的支援

  • #370:增加了 XML 名稱空間中的屬性佔位符支援

  • #392:增加了文件測試支援

  • #401:切換到 assertj

  • 從 JIRA 遷移到 GitHub Issues

  • 增加了 Gitter Chat

2.0 版本的新特性

儘管 Spring LDAP API 在 2.0 版本中進行了相當重大的現代化改造,但已盡力確保儘可能向後相容。除了少數例外,使用 Spring LDAP 1.3.x 的程式碼在使用 2.0 庫時應無需任何修改即可編譯和執行。

例外情況是少數類已移至新包,以便實現一些重要的重構。這些已移動的類通常不屬於預期的公共 API,遷移過程應該順利。如果在升級後找不到 Spring LDAP 類,您應該在 IDE 中整理匯入。

不過,您應該會遇到一些棄用警告,並且還有許多其他 API 改進。為了充分利用 2.0 版本,建議您放棄棄用的類和方法,並遷移到新的、改進的 API 實用程式。

以下列表簡要描述了 Spring LDAP 2.0 中最重要的更改:

  • Spring LDAP 現在需要 Java 6。Spring 2.0 及更高版本仍然受支援。

  • 核心 API 已更新,支援 Java 5+ 特性,如泛型和可變引數。因此,整個 spring-ldap-tiger 模組已被棄用,我們鼓勵您遷移到使用核心 Spring LDAP 類。核心介面的引數化會導致現有程式碼中出現大量編譯警告,我們鼓勵您採取適當措施來消除這些警告。

  • ODM(物件目錄對映)功能已移至核心,並且 LdapOperationsLdapTemplate 中有新方法使用這種到 ODM 註解類的自動轉換。有關更多資訊,請參閱 物件目錄對映 (ODM)

  • 現在(終於)提供了自定義 XML 名稱空間以簡化 Spring LDAP 的配置。有關更多資訊,請參閱 [配置]

  • Spring LDAP 現在支援 Spring Data Repository 和 QueryDSL。有關更多資訊,請參閱 Spring LDAP 倉庫

  • DirContextAdapter 和 ODM 中,Name 例項作為屬性值現在已針對可分辨名稱相等性得到正確處理。有關更多資訊,請參閱 DirContextAdapter 和作為屬性值的可分辨名稱以及 ODM 和作為屬性值的可分辨名稱

  • DistinguishedName 及相關類已棄用,取而代之的是標準的 Java LdapName。有關該庫如何幫助使用 LdapName 物件的資訊,請參閱 動態構建可分辨名稱

  • 已新增流暢的 LDAP 查詢構建支援。這使得在 Spring LDAP 中處理 LDAP 搜尋時程式設計體驗更加愉快。有關 LDAP 查詢構建器支援的更多資訊,請參閱 構建 LDAP 查詢高階 LDAP 查詢

  • LdapTemplate 中舊的 authenticate 方法已被棄用,取而代之的是幾個新的 authenticate 方法,它們與 LdapQuery 物件一起使用,並在身份驗證失敗時丟擲異常,從而使使用者更容易找出導致身份驗證嘗試失敗的原因。

  • 示例已進行了完善和更新,以利用 2.0 中的功能。為了提供一個有用的 LDAP 使用者管理應用程式示例,投入了相當多的精力。

  • 添加了 LdapClient.create(LdapTemplate) 以簡化從 LdapTemplate 構造 LdapClient

打包概述

至少,要使用 Spring LDAP,您需要以下內容:

  • spring-ldap-core:Spring LDAP 庫

  • spring-core:框架內部使用的各種實用程式類

  • spring-beans:用於操作 Java bean 的介面和類

  • slf4j:一個簡單的日誌門面,內部使用

除必需的依賴項外,某些功能還需要以下可選依賴項:

  • spring-data-ldap:倉庫支援等基礎設施

  • spring-context:如果您的應用程式透過 Spring 應用程式上下文連線,則需要它。spring-context 增加了應用程式物件使用一致的 API 獲取資源的能力。如果您計劃使用 BaseLdapPathBeanPostProcessor,則絕對需要它。

  • spring-tx:如果您計劃使用客戶端補償事務支援,則需要它。

  • spring-jdbc:如果您計劃使用客戶端補償事務支援,則需要它。

  • commons-pool:如果您計劃使用池化功能,則需要它。

  • spring-batch:如果您計劃將 LDIF 解析功能與 Spring Batch 一起使用,則需要它。

spring-data-ldap 間接添加了 spring-repository.xsdspring-ldap.xsd 使用了它。因此,即使不使用 Spring Data 的功能集,Spring LDAP 的 XML 配置支援也需要此依賴項。

入門

示例提供了一些關於如何將 Spring LDAP 用於常見用例的有用示例。

支援

如果您有任何問題,請在 Stack Overflow 上使用 spring-ldap 標籤提問。專案網頁是 spring.io/spring-ldap/

致謝

Spring LDAP 專案啟動時的最初努力由 Jayway 贊助。該專案的當前維護由 Pivotal 資助,該公司後來被 VMware 收購。

感謝 Structure101 提供了開源許可證,這對保持專案結構井然有序非常有用。

© . This site is unofficial and not affiliated with VMware.