Подтвердить что ты не робот

Лучшая практика настройки Spring LdapTemplate через аннотации вместо XML?

Для приложения Spring Boot, я успешно настроил Spring LdapTemplate с помощью аннотаций, включая зависимость LdapContextSource с @Value от application.properties. (Woot! Я не мог найти пример, так что, возможно, это поможет другим.)

Фрагменты (ниже) настраивают источник контекста, вставляют его в LdapTemplate и autwire, что в моем DirectoryService.

Есть ли лучший/более чистый способ настройки ContextSource в загрузочном приложении Spring?

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;
    }
}
4b9b3361

Ответ 1

Почему все подклассы? Просто используйте конфигурацию для настройки beans. Либо 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 автоматически.

Общее правило состоит в том, что вы не хотите расширять инфраструктуру beans (например, DataSource или LdapTemplate), но настраивать их явно. Это в отличие от вашего приложения beans (службы, репозитории и т.д.).