@Data @Entry(base = "ou=people,dc=didispace,dc=com", objectClasses = "inetOrgPerson") public class Person { @Id private Name id; @DnAttribute(value = "uid", index = 3) private String uid; @Attribute(name = "cn") private String commonName; @Attribute(name = "sn") private String suerName; private String userPassword; } public interface PersonRepository extends CrudRepository<Person, Name> { }
经过上面的定义以后,已经将Person对象与LDAP存储内容实现了映射,咱们只须要使用PersonRepository
就能够轻松的对LDAP内容实现读写。html
@RunWith(SpringRunner.class) @SpringBootTest public class ApplicationTests { @Autowired private PersonRepository personRepository; @Test public void findAll() throws Exception { personRepository.findAll().forEach(p -> { System.out.println(p); }); } }
启动该测试用例以后,咱们能够看到控制台中输出了刚才维护在ldap-server.ldif
中的用户信息:spring
2018-01-27 14:25:06.283 WARN 73630 --- [ main] o.s.ldap.odm.core.impl.ObjectMetaData : The Entry class Person should be declared final Person(id=uid=ben,ou=people,dc=didispace,dc=com, uid=ben, commonName=didi, suerName=zhaiyongchao, userPassword=123,83,72,65,125,110,70,67,101,98,87,106,120,102,97,76,98,72,72,71,49,81,107,53,85,85,52,116,114,98,118,81,61)
经过上面的入门示例,若是您可以独立完成,那么在Spring Boot中操做LDAP的基础目标已经完成了。服务器
若是您足够了解Spring Data,其实不难想到,这个在其下的子项目必然也遵照Repsitory的抽象。因此,咱们能够使用上面定义的PersonRepository
来轻松实现操做,好比下面的代码就能够方便的往LDAP中添加用户:单元测试
Person person = new Person(); person.setUid("uid:1"); person.setSuerName("AAA"); person.setCommonName("aaa"); person.setUserPassword("123456"); personRepository.save(person);
若是还想实现更多操做,您能够参考spring-data-ldap的文档来进行使用。测试
在本文的例子中都采用了嵌入式的LDAP服务器,事实上这种方式也仅限于咱们本地测试开发使用,真实环境下LDAP服务端必然是独立部署的。ui
在Spring Boot的封装下,咱们只须要配置下面这些参数就能将上面的例子链接到远端的LDAP而不是嵌入式的LDAP。url
spring.ldap.urls=ldap://localhost:1235 spring.ldap.base=dc=didispace,dc=com spring.ldap.username=didispace spring.ldap.password=123456
源码来源spa