Best practice for configuring Spring LdapTemplate via annotations instead of XML?

半世苍凉 提交于 2019-11-28 04:56:47

Why all the subclasses? Just use configuration to configure the beans. Either XML or 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());        
    }

}

Your DirectoryService can remain the same as it will have the LdapTemplate autowired.

A general rule of thumb is that you don't want to extend your infrastructure beans (like DataSource or LdapTemplate) but configure them explicitly. This as opposed to your application beans (services, repositories etc.).

Explicit wiring up of your LDAP isn't necessary at all for straight forward cases. This is the sort of thing Spring Boot aims to eliminate by being opinionated in the first place.

Ensure you have the spring-boot-starter-data-ldap or the spring-ldap-core dependency included, e.g. for Maven in your pom:xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>

Configure your LDAP in application.properties with the following keys:

# Note the spring prefix for each and use just the CN for username
spring.ldap.url=ldap://server.domain.com:389
spring.ldap.base=OU=Employees,OU=Users,DC=domain,DC=com
spring.ldap.username=myuserid
spring.ldap.password=secretthingy

Then simply rely on Spring to autowire, e.g. using field injection1:

@Autowired
private final LdapTemplate ldapTemplate;

Reference: Spring Boot Reference Guide: LDAP


1 Field injection is generally not recommended but it's used here for concision.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!