Ldap Query - Configuration using Spring Boot

James picture James · Sep 23, 2014 · Viewed 16.1k times · Source

I have a Spring boot application that needs to perform LDAP queries. I'm trying to take the following recommendation from the Spring boot documentation:

"Many Spring configuration examples have been published on the Internet that use XML configuration. Always try to use the equivalent Java-base configuration if possible."

In a Spring XML configuration file, I would have used:

 <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>

How would I configure this using a Java-based configuration? I need to be able to change URL, base, username, and password attributes of ldap:context-source without a code rebuild.

Answer

Andy Wilkinson picture Andy Wilkinson · Sep 24, 2014

The <ldap:context-source> XML tag produces an LdapContextSource bean and the <ldap:ldap-template> XML tag produces an LdapTemplate bean so that's what you need to do in your Java configuration:

@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;
    }
}

To allow you to change the configuration without a rebuild of your code, I've used Spring Boot's @ConfigurationProperties. This will look in your application's environment for properties prefixed with ldap.contextSource and then apply them to the LdapContextSource bean by calling the matching setter methods. To apply the configuration in the question, you can use an application.properties file with four 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