2014-09-23 191 views
4

我有一个需要执行LDAP查询的Spring启动应用程序。我试图从春天启动文档以下建议:Ldap查询 - 使用Spring Boot的配置

“许多Spring配置例子已经公布的 互联网使用XML配置上始终尝试使用等效 Java的基本配置,如果可能。”

在Spring XML配置文件,我会用:

<ldap:context-source 
      url="ldap://localhost:389" 
      base="cn=Users,dc=test,dc=local" 
      username="cn=testUser" 
      password="testPass" /> 

    <ldap:ldap-template id="ldapTemplate" /> 

    <bean id="personRepo" class="com.llpf.ldap.PersonRepoImpl"> 
     <property name="ldapTemplate" ref="ldapTemplate" /> 
    </bean> 

我将如何配置此使用基于Java的配置?我需要能够更改ldap:context-source的URL,基址,用户名和密码属性,而无需重建代码。

回答

18

<ldap:context-source> XML标签产生LdapContextSource bean和<ldap:ldap-template> XML标签产生LdapTemplate豆所以这就是你需要在Java配置做什么:

@Configuration 
@EnableAutoConfiguration 
@EnableConfigurationProperties 
public class Application { 

    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
    } 

    @Bean 
    @ConfigurationProperties(prefix="ldap.contextSource") 
    public LdapContextSource contextSource() { 
     LdapContextSource contextSource = new LdapContextSource(); 
     return contextSource; 
    } 

    @Bean 
    public LdapTemplate ldapTemplate(ContextSource contextSource) { 
     return new LdapTemplate(contextSource); 
    } 

    @Bean 
    public PersonRepoImpl personRepo(LdapTemplate ldapTemplate) { 
     PersonRepoImpl personRepo = new PersonRepoImpl(); 
     personRepo.setLdapTemplate(ldapTemplate); 
     return personRepo; 
    } 
} 

要允许您更改配置,而无需重建你的代码,我用过Spring Boot的@ConfigurationProperties。这会在您的应用程序环境中查找以ldap.contextSource为前缀的属性,然后通过调用匹配的setter方法将它们应用于LdapContextSource bean。要在问题应用配置,您可以使用application.properties文件有四个属性:

ldap.contextSource.url=ldap://localhost:389 
ldap.contextSource.base=cn=Users,dc=test,dc=local 
ldap.contextSource.userDn=cn=testUser 
ldap.contextSource.password=testPass 
+0

奇数 - 如果我创建一个yaml配置文件,我无法得到这个工作 - 当我创建一个属性配置时它工作正常。 – joensson 2015-02-03 10:21:36

+1

它也与yaml配置文件一起工作。 'ldap.contextSource: url:ldap:// localhost:389 base:cn = Users,dc = test,dc = local userDn:cn = testUser password:testPass' – niro 2015-09-18 03:34:52

-2

在XML中,你可以使用:

<bean id="ldapContextSource" 
     class="org.springframework.ldap.core.support.LdapContextSource"> 
    <property name="url" value="<URL>" /> 
    <property name="base" value="<BASE>" /> 
    <property name="userDn" value="CN=Bla,OU=com" /> 
    <property name="password" value="<PASS>" /> 
    <property name="referral" value="follow" /> 
</bean> 

<bean id="ldapTemplate" 
     class="org.springframework.ldap.core.LdapTemplate" 
     depends-on="ldapContextSource"> 
     <constructor-arg index="0" ref="ldapContextSource" /> 
     <property name="ignorePartialResultException" value="true"/> 
</bean> 

<bean id="personRepo" class="com.llpf.ldap.PersonRepoImpl"> 
     <property name="ldapTemplate" ref="ldapTemplate" /> 
</bean> 

我希望它能帮助!

+0

这没有帮助。这完全不是他想要的。 – 2017-05-30 20:08:34