对于Spring Boot应用程序,我LdapTemplate使用 批注 成功配置了Spring ,其中包括application.properties中LdapContextSource带有@Values 的依赖项。(糟糕!我找不到示例,所以也许这会对其他人有所帮助。)
LdapTemplate
LdapContextSource
@Value
片段(如下所示)设置了上下文源,将其注入LdapTemplate,然后自动将其连接到我的DirectoryService中。
ContextSource 在Spring Boot应用程序中是否有更好/更干净的方法来设置?
ContextSource
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); } }
DirectoryService.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; } }
为什么是所有子类?只需使用配置来配置bean。XML或Java Config。
@Configuration public class LdapConfiguration { @Autowired Environment env; @Bean public LdapContextSource contextSource () { LdapContextSource contextSource= new LdapContextSource(); contextSource.setUrl(env.getRequiredProperty("ldap.url")); contextSource.setBase(env.getRequiredProperty("ldap.base")); contextSource.setUserDn(env.getRequiredProperty("ldap.user")); contextSource.setPassword(env.getRequiredProperty("ldap.password")); return contextSource; } @Bean public LdapTemplate ldapTemplate() { return new LdapTemplate(contextSource()); } }
您DirectoryService可以保持与LdapTemplate自动接线相同。
DirectoryService
一般的经验法则是,您不想扩展基础结构Bean(如DataSource或LdapTemplate),而是显式配置它们。与您的应用程序Bean(服务,存储库等)相反。
DataSource