|
对于最新的稳定版本,请使用 Spring Data LDAP 4.0.4! |
配置
本节介绍如何配置 Spring Data LDAP。
Spring LDAP 仓库可以通过在 XML 配置中使用 <data-ldap:repositories> 标签,或在配置类上使用 @EnableLdapRepositories 注解来启用:
-
“Spring 命名空间”(XML 配置)
-
“基于注解的配置”(Java 配置)
若要在自动生成的仓库中包含对 LdapQuery 参数的支持,请让您的接口继承 LdapRepository,而不是 CrudRepository。
所有 Spring LDAP 仓库都必须使用带有 ODM 注解的实体,如对象-目录映射(Object-Directory Mapping)中所述。
由于所有ODM管理的类都必须使用一个专有名称(Distinguished Name)作为ID,因此所有Spring LDAP仓库的ID类型参数都必须设置为javax.naming.Name。
确实,内置的 LdapRepository 仅接受一个类型参数:即被管理的实体类,其默认 ID 为 javax.naming.Name。
由于 LDAP 协议的特性,Spring LDAP 仓库不支持分页和排序。
您必须使用 ODM 注解,例如 org.springframework.ldap.odm.annotations.Id。
使用 Spring Data 的注解是无效的,因为 Spring LDAP 使用其自身的映射层。 |
基于注解的配置
Spring Data LDAP 仓库的支持可以通过 JavaConfig 以及自定义的 XML 命名空间来激活,如下例所示:
@Configuration
@EnableLdapRepositories("com.acme.*.repositories")
class MyConfig {
@Bean
ContextSource contextSource() {
LdapContextSource ldapContextSource = new LdapContextSource();
ldapContextSource.setUserDn("cn=Admin");
ldapContextSource.setPassword("secret");
ldapContextSource.setUrl("ldap://127.0.0.1:389");
return ldapContextSource;
}
@Bean
LdapTemplate ldapTemplate(ContextSource contextSource) {
return new LdapTemplate(contextSource);
}
}
此配置会扫描基础包,查找继承了 LDAP 仓库的接口,并为每个找到的接口创建 Spring Bean。
如果未配置基础包,基础设施将扫描带注解的配置类所在的包。
Spring 命名空间
Spring Data 的 LDAP 模块包含一个自定义命名空间,可用于定义仓库 Bean。
该模块还包含一些专属于 LDAP 的特性和元素属性。
通常,可以通过使用 repositories 元素来配置 LDAP 仓库,如下例所示:
<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"
xmlns:data-ldap="http://www.springframework.org/schema/data/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
http://www.springframework.org/schema/data/ldap
https://www.springframework.org/schema/data/ldap/spring-ldap.xsd">
<ldap:context-source url="ldap://127.0.0.1:389"
username="cn=Admin"
password="secret" />
<ldap:ldap-template />
<data-ldap:repositories base-package="com.acme.*.repositories" />
</beans>
此配置会扫描基础包,查找继承了 LDAP 仓库的接口,并为每个找到的接口创建 Spring Bean。
默认情况下,仓库会自动装配一个名为 LdapTemplate 的 ldapTemplate Spring Bean,因此只有在不遵循此约定时,才需要显式配置 ldap-template-ref。
| JavaConfig 和 XML 哪个更好? XML 是 Spring 早期的配置方式。 在当今 Java 快速发展、记录类型(record types)、注解(annotations)等特性不断涌现的时代,新项目通常会尽可能多地使用纯 Java 配置。 尽管目前尚无立即移除 XML 支持的计划,但一些最新特性可能无法通过 XML 使用。 |
使用 repositories 元素会按照 创建 Repository 实例 中所述的方式查找 Spring Data 仓库。
自定义命名空间属性
除了repositories元素的默认属性之外,LDAP 命名空间还提供了其他属性,使您能够更细致地控制存储库的设置:
|
显式地将 |
Spring Data LDAP 需要一个名为 LdapMappingContext 的 ldapMappingContext Bean 存在。
如果未定义此类 Bean,则 Spring Data LDAP 会在应用程序上下文中注册一个默认实例。 |