小编典典

Spring注解@ Entry.base不支持SpEL

spring-boot

我使用Spring Data LDAP,并且Spring Boot为嵌入式UnboundID服务器提供了开箱即用的支持。但是,当我使用Spring Data
LDAP的@Entry注释时,我需要base根据使用的是嵌入式UnboundID LDAP服务器还是远程Active
Directory服务器,在注释中指定其他内容。

我正在尝试通过指定以下内容来使用SpEL和基于配置文件的属性:

@Entry(base = "${ldap.person.base}", ...)

然后我有一个application.propretieswith ldap.person.base=OU=AD Person Base和一个application-embedded.propertieswith ldap.person.base=OU=Embedded Person Base

但是,@Entry注释似乎不支持SpEL评估:

javax.naming.InvalidNameException:无效名称:$ {ldap.person.base}

Spring LDAP中有一个开放的问题来添加对此的支持,但是在Spring LDAP中支持它之前,是否有任何解决方法或其他方法可以实现此目的?


阅读 896

收藏
2020-05-30

共1个答案

小编典典

原来我之所以需要与众不同的原因base是因为Spring并未在base上设置ContextSource

当您让Spring
Boot自动配置嵌入式LDAP服务器时,它将在中创建一个ContextSource这样的目录EmbeddedLdapAutoConfiguration

@Bean
@DependsOn("directoryServer")
@ConditionalOnMissingBean
public ContextSource ldapContextSource() {
    LdapContextSource source = new LdapContextSource();
    if (hasCredentials(this.embeddedProperties.getCredential())) {
        source.setUserDn(this.embeddedProperties.getCredential().getUsername());
        source.setPassword(this.embeddedProperties.getCredential().getPassword());
    }
    source.setUrls(this.properties.determineUrls(this.environment));
    return source;
}

如您所见,它在那里没有调用source.setBase()。因此,为解决此问题,我添加了一个配置文件,@Profile("embedded")并手动创建了一个ContextSourcebase自己设置的位置(我省略了凭据部分,因为我不对嵌入式服务器使用凭据):

@Configuration
@Profile("embedded")
@EnableConfigurationProperties({ LdapProperties.class })
public class EmbeddedLdapConfig {

    private final Environment environment;
    private final LdapProperties properties;

    public EmbeddedLdapConfig(final Environment environment, final LdapProperties properties) {
        this.environment = environment;
        this.properties = properties;
    }

    @Bean
    @DependsOn("directoryServer")
    public ContextSource ldapContextSource() {
        final LdapContextSource source = new LdapContextSource();
        source.setUrls(this.properties.determineUrls(this.environment));
        source.setBase(this.properties.getBase());
        return source;
    }
}

现在,对于Active
Directory服务器和嵌入式UnboundID服务器,我可以将base属性值保留在@Entry相同的位置,并且它可以正常工作。

2020-05-30