通过注释而不是XML配置Spring LdapTemplate的最佳实践?
2022-09-01 06:39:21
对于Spring Boot应用程序,我使用注释成功配置了Spring,包括与s from application.properties的依赖关系。(呜呜!我找不到例子,所以也许这会帮助其他人。LdapTemplate
LdapContextSource
@Value
代码段(如下)设置上下文源,将其注入到 中,然后将其自动连接到我的 DirectoryService 中。LdapTemplate
有没有更好/更简洁的方法在Spring Boot应用程序中设置上下文源
?
application.properties(在类路径上):
ldap.url=ldap://server.domain.com:389
ldap.base:OU=Employees,OU=Users,DC=domain,DC=com
ldap.username:CN=myuserid,OU=employees,OU=Users,DC=domain,DC=com
ldap.password:secretthingy
MyLdapContextSource.java :
@Component
public class MyLdapContextSource extends LdapContextSource implements ContextSource {
@Value("${ldap.url}")
@Override
public void setUrl(String url) { super.setUrl(url); }
@Value("${ldap.base}")
@Override
public void setBase(String base) {super.setBase(base); }
@Value("${ldap.username}")
@Override
public void setUserDn(String userDn) {super.setUserDn(userDn); }
@Value("${ldap.password}")
@Override
public void setPassword(String password) { super.setPassword(password); }
}
MyLdapTemplate.java:
@Component
public class MyLdapTemplate extends LdapTemplate {
@Autowired
public MyLdapTemplate(ContextSource contextSource) { super(contextSource); }
}
目录服务.java:
@Service
public class DirectoryService {
private final LdapTemplate ldapTemplate;
@Value("${ldap.base}")
private String BASE_DN;
@Autowired
public DirectoryService(LdapTemplate ldapTemplate) { this.ldapTemplate = ldapTemplate; }
public Person lookupPerson(String username) {
return (Person) ldapTemplate.lookup("cn=" + username, new PersonAttributesMapper());
}
public List<Person> searchDirectory(String searchterm) {
SearchControls searchControls = new SearchControls();
searchControls.setCountLimit(25);
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
List<Person> people = (List<Person>) ldapTemplate.search(
BASE_DN, "cn=" + searchterm, searchControls, new PersonAttributesMapper());
return people;
}
}