Настройте второй независимый LdapTemplate для Spring Boot - PullRequest
0 голосов
/ 26 сентября 2018

Мне нужно добавить второй шаблон LdapTemplate в существующую кодовую базу.Каталоги LDAP совершенно разные и ничего не разделяют.

Другие, похоже, имеют аналогичные потребности: https://github.com/spring-projects/spring-ldap/issues/409. Я нашел Несколько репозиториев LDAP с репозиторием Spring LDAP и добавили второй наборЗаписи конфигурации LDAP как spring.ldap2. и этот дополнительный класс конфигурации:

@Configuration
public class LdapConfig {
    @Autowired
    private Environment environment;

    @Bean(name = "ldapProperties2")
    @ConfigurationProperties(prefix = "spring.ldap2")
    public LdapProperties ldapProperties() {
        return new LdapProperties();
    }

    @Bean(name = "contextSource2")
    public LdapContextSource contextSourceTarget(@Qualifier("ldapProperties2") LdapProperties ldapProperties) {
        LdapContextSource source = new LdapContextSource();
        source.setUserDn(ldapProperties.getUsername());
        source.setPassword(ldapProperties.getPassword());
        source.setBase(ldapProperties.getBase());
        source.setUrls(ldapProperties.determineUrls(this.environment));
        source.setBaseEnvironmentProperties(
                Collections.<String, Object>unmodifiableMap(ldapProperties.getBaseEnvironment()));
        return source;
    }

    @Bean(name = "ldapTemplate2")
    public LdapTemplate ldapTemplate(@Qualifier("contextSource2") LdapContextSource contextSource) {
        return new LdapTemplate(contextSource);
    }
}

Boot жалуется:

Parameter 0 of constructor in org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration required a single bean, but 2 were found:
    - ldapProperties2: defined by method 'ldapProperties' in class path resource [my/company/foo/LdapConfig.class]
    - spring.ldap-org.springframework.boot.autoconfigure.ldap.LdapProperties: defined in null

Я пытался добавить @Primary, но это также можно добавить в мой класси весь существующий код уже использует «старый» первичный шаблон.К сожалению, нет @Second.

РЕДАКТИРОВАТЬ

Я сделал больше попыток:

@Autowired
@Qualifier("ldapTemplate1")
LdapTemplate ad;

@Autowired
@Qualifier("ldapTemplate2")
LdapTemplate gd;

Первый бин:

@Bean(name="ldapTemplate1")
public LdapTemplate ldapTemplate(@Qualifier("contextSource1") LdapContextSource contextSource) {
    return new LdapTemplate(contextSource);
}

Второй компонент:

@Bean(name = "ldapTemplate2")
    public LdapTemplate ldapTemplate(@Qualifier("contextSource2") LdapContextSource contextSource) {
        return new LdapTemplate(contextSource);
    }

Тогда Spring Boot жалуется на это:

Field ad in com.example... required a bean of type 'org.springframework.ldap.core.LdapTemplate' that could not be found.
    - Bean method 'ldapTemplate' in 'LdapDataAutoConfiguration' not loaded because @ConditionalOnMissingBean (types: org.springframework.ldap.core.LdapOperations; SearchStrategy: all) found beans of type 'org.springframework.ldap.core.LdapOperations' ldapTemplate2
    - User-defined bean method 'ldapTemplate' in 'LdapConfiguration2'

Даже когда я переименовываю оба из них в LdapTemplate Spring Boot не может выполнить автоматическое подключение.

Как я могу автоматически настроить два независимых LdapTemplate s?Я использую Spring Boot 2.0.5

1 Ответ

0 голосов
/ 15 октября 2018

Это подход, который я использовал в приложении, развернутом на Tomcat 8.5 с Spring 4 и Spring LDAP.

beans.xml:

<beans:bean id="contextSource-one"
    class="org.springframework.ldap.pool2.factory.PooledContextSource">
    <beans:constructor-arg>
        <beans:bean class="org.springframework.ldap.pool2.factory.PoolConfig"
        p:testOnBorrow="true" p:minEvictableIdleTimeMillis="300000" p:maxWaitMillis="5000" />
    </beans:constructor-arg>
    <beans:property name="contextSource">
        <beans:bean
            class="...ContextSource"...>
        </beans:bean>
    </beans:property>
    <beans:property name="dirContextValidator">
        <beans:bean
            class="org.springframework.ldap.pool2.validation.DefaultDirContextValidator" />
    </beans:property>
</beans:bean>

<beans:bean id="contextSource-two"
    class="org.springframework.ldap.pool2.factory.PooledContextSource">
    <beans:constructor-arg>
        <beans:bean class="org.springframework.ldap.pool2.factory.PoolConfig"
        p:testOnBorrow="true" p:minEvictableIdleTimeMillis="300000" p:maxWaitMillis="5000" />
    </beans:constructor-arg>
    <beans:property name="contextSource">
        <beans:bean
            class="...ContextSource"...>
        </beans:bean>
    </beans:property>
    <beans:property name="dirContextValidator">
        <beans:bean
            class="org.springframework.ldap.pool2.validation.DefaultDirContextValidator" />
    </beans:property>
</beans:bean>

Адаптация к вашим потребностям и / илипреобразовать в конфигурацию Java.

Вот зависимый класс, почти как ваш:

public class MyClass {
    private List<LdapTemplate> ldapTemplates;

    @Autowired
    public MyClass(List<ContextSource> contextSources) {
        this.ldapTemplates = new LinkedList<>();
        for (ContextSource cs : contextSources)
            this.ldapTemplates.add(new LdapTemplate(cs));
    }
}
...