无法解析值“ classpath:/ ldap-$ {spring.profiles.active} .properties”中的占位符“ spring.profiles.active”

时间:2018-08-21 07:24:52

标签: java spring spring-boot application.properties

我正在尝试从ldap-TEST.properties文件读取ldap属性 并尝试将其绑定到我指定的java config class.for @PropertSource并为propertysourcesplaceholderconfigurer定义了一个静态Bean。 仍然我在下面的值“ classpath:/ ldap-$ {spring.profiles.active} .properties”中无法解析占位符“ spring.profiles.active”是项目文件,请帮助我

@Configuration
@PropertySource("classpath:/ldap-${spring.profiles.active}.properties")
public class LdapConfig { 
 @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.userDn"));
    contextSource.setPassword(env.getRequiredProperty("ldap.password"));
    contextSource.afterPropertiesSet();
    return contextSource;
}

@Bean
public LdapTemplate ldapTemplate() {
    return new LdapTemplate(contextSource());
}

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

}

//ldap-TEST.properties file
ldap.base=dc=example,dc=com
ldap.password=password
ldap.port=839
ldap.userDn=cn=read-only-admin,dc=example,dc=com
ldap.url=ldap://ldap.forumsys.com:389

我的主要应用

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
       SpringApplication.run(Application.class, args);
 }

}

2 个答案:

答案 0 :(得分:0)

在Spring的Type注释的字符串值内不能使用诸如${spring.profiles.active}之类的属性。此类属性将被注入到@Value之类的用于属性或方法的注释中。

答案 1 :(得分:0)

spring.profiles.active后面的值实际上是一个数组。因此,即使正确地扩展了该值,在某些情况下,它也可能无法按您想要的方式工作。

如果通过@PropertySource配置的路径与application.properties|yml的工作方式相同,那就很好了,但是目前并非如此(有an active issue on GitHub )。因此,必须考虑替代方案:

  1. 最简单的选择是使用常规文件名application.properties|ymlapplication-{profile}.properties|yml。我看不出没有这样做的充分理由,但是我不知道您的项目要求,所以...
  2. 稍微复杂一点,使用Java代码获取已配置的配置文件,然后以编程方式配置Spring环境。 See this SO answer for more details