1. 简介

本文将深入探讨 Spring Data LDAP 的集成与配置。如果你需要 Spring LDAP 的基础入门教程,建议先阅读这篇文章。关于 Spring Data JPA 的概览,可以参考这里

2. Maven 依赖

首先添加必要的 Maven 依赖:

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-ldap</artifactId>
    <version>3.1.5</version>
</dependency>

最新版本可在 spring-data-ldap 查找。

3. 域实体映射

Spring LDAP 通过对象目录映射(ODM)实现 LDAP 条目到 Java 对象的转换。下面定义实体类,用于映射已在Spring LDAP 文章中配置的 LDAP 目录:

@Entry(
  base = "ou=users", 
  objectClasses = { "person", "inetOrgPerson", "top" })
public class User {
    @Id
    private Name id;
    
    private @Attribute(name = "cn") String username;
    private @Attribute(name = "sn") String password;

    // 标准getter/setter
}

@Entry 类似 JPA/ORM 中的 @Entity,用于指定实体映射的 LDAP 条目根目录
⚠️ 实体类必须在 javax.naming.Name 类型的字段上声明 @Id 注解,表示实体的 DN(Distinguished Name)
@Attribute 注解用于将对象类字段映射到实体字段

4. Spring Data 仓库

Spring Data Repository 是抽象层,为多种持久化存储提供开箱即用的数据访问层实现。Spring 框架内部自动实现了数据仓库的 CRUD 操作,完整细节可参考Spring Data JPA 入门

Spring Data LDAP 提供类似抽象,自动实现包含 LDAP 目录基本 CRUD 操作的Repository接口。同时支持基于方法名创建自定义查询

定义 User 实体的仓库接口:

@Repository
public interface UserRepository extends LdapRepository<User> {
    User findByUsername(String username);
    User findByUsernameAndPassword(String username, String password);
    List<User> findByUsernameLikeIgnoreCase(String username);
}

✅ 继承 LdapRepository 后,Spring Data 自动提供 find()findAll()save()delete() 等基础方法
✅ 自定义方法通过查询构建机制自动实现

5. 配置方式

支持基于 Java 的 @Configuration 类或 XML 命名空间配置。这里使用 Java 配置:

@Configuration
@EnableLdapRepositories(basePackages = "com.baeldung.ldap.**")
public class AppConfig {
}

@EnableLdapRepositories 提示 Spring 扫描指定包中标记为 @Repository 的接口。

6. Spring Boot 集成

**在 Spring Boot 项目中,使用 Spring Boot Starter Data Ldap 依赖可自动配置 LdapContextSourceLdapTemplate**。

在 pom.xml 添加依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>

在 application.properties 配置连接参数:

spring.ldap.url=ldap://localhost:18889
spring.ldap.base=dc=example,dc=com
spring.ldap.username=uid=admin,ou=system
spring.ldap.password=secret

⚠️ 更多自动配置细节参考官方文档。Spring Boot 通过 LdapAutoConfiguration 自动装配 LdapTemplate,可直接注入:

@Autowired
private LdapTemplate ldapTemplate;

7. 业务逻辑实现

定义使用 UserRepository 操作 LDAP 目录的服务类:

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    // 业务方法
}

7.1 用户认证

实现简单的用户认证逻辑:

public Boolean authenticate(String u, String p) {
    return userRepository.findByUsernameAndPassword(u, p) != null;
}

7.2 用户创建

创建新用户并存储密码哈希:

public void create(String username, String password) {
    User newUser = new User(username,digestSHA(password));
    newUser.setId(LdapUtils.emptyLdapName());
    userRepository.save(newUser);
}

⚠️ 实际项目中应使用 digestSHA 等安全方式处理密码

7.3 用户修改

修改现有用户信息:

public void modify(String u, String p) {
    User user = userRepository.findByUsername(u);
    user.setPassword(p);
    userRepository.save(user);
}

7.4 用户搜索

使用自定义方法搜索用户:

public List<String> search(String u) {
    List<User> userList = userRepository
      .findByUsernameLikeIgnoreCase(u);
    
    if (userList == null) {
        return Collections.emptyList();
    }

    return userList.stream()
      .map(User::getUsername)
      .collect(Collectors.toList());  
}

8. 实战示例

测试简单的认证场景:

@Test
public void givenLdapClient_whenCorrectCredentials_thenSuccessfulLogin() {
    Boolean isValid = userService.authenticate(USER3, USER3_PWD);
 
    assertEquals(true, isValid);
}

9. 总结

本教程演示了 Spring LDAP 仓库配置和 CRUD 操作的基础用法。完整示例代码可在 GitHub 获取。


原始标题:Guide to Spring Data LDAP