【发布时间】:2018-10-15 22:13:07
【问题描述】:
我需要向现有代码库添加第二个 LdapTemplate。 LDAP 目录完全不同,不共享任何内容。
其他人似乎也有类似需求:https://github.com/spring-projects/spring-ldap/issues/409。我找到了 Multiple LDAP repositories with Spring LDAP Repository 并添加了第二组 LDAP 配置条目为 spring.ldap2. 和这个额外的 Config 类:
@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);
}
}
启动抱怨:
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:
@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 也无法自动装配。
如何自动配置两个独立的 LdapTemplates ?我正在使用 Spring Boot 2.0.5
【问题讨论】:
-
我稍后会看看这个并展示它是如何工作的。
-
谢谢,那真的很有帮助
-
它是否适用于 1 个模板?尝试删除 @Bean(name = "ldapProperties2") @ConfigurationProperties(prefix = "spring.ldap2") public LdapProperties ldapProperties() { return new LdapProperties(); }
-
并删除@Qualifier("ldapProperties2") LdapProperties ldapProperties。手动输入属性值并检查它会抛出什么。
标签: spring spring-boot ldap spring-ldap