Ldap查询 - 使用Spring Boot进行配置

Jam*_*mes 7 spring-ldap spring-boot

我有一个需要执行LDAP查询的Spring启动应用程序.我试图从Spring启动文档中获取以下建议:

"许多Spring配置示例已在Internet上发布,使用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>
Run Code Online (Sandbox Code Playgroud)

我如何使用基于Java的配置来配置它?我需要能够在没有代码重建的情况下更改ldap:context-source的URL,base,username和password属性.

And*_*son 20

<ldap:context-source>XML标签产生LdapContextSourcebean和<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;
    }
}
Run Code Online (Sandbox Code Playgroud)

为了允许您在不重建代码的情况下更改配置,我使用了Spring Boot @ConfigurationProperties.这将在应用程序的环境中查找带有前缀的属性ldap.contextSource,然后LdapContextSource通过调用匹配的setter方法将它们应用于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
Run Code Online (Sandbox Code Playgroud)

  • 它也适用于 yaml 配置文件。`ldap.contextSource: url: ldap://localhost:389 base: cn=Users,dc=test,dc=local userDn: cn=testUser 密码: testPass` (2认同)