【问题标题】:Spring Boot PropertyPlaceholderConfigurer Not Available from EnvironmentSpring Boot PropertyPlaceholderConfigurer 在环境中不可用
【发布时间】:2018-05-29 21:41:39
【问题描述】:

由于组织限制,我仅限于作为 WAR 文件部署到 Tomcat 服务器,我们使用标准做法 {applicationName}.properties 捆绑在 WAR 中,然后 Tomcat 服务器有一个 {applicationName}-override.properties类路径。

我有以下 bean 定义来加载属性。

    @Bean
    public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
        PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
        Resource[] resources = new Resource[2];
        resources[0] = new ClassPathResource("parameter-portal.properties");
        resources[1] = new ClassPathResource("parameter-portal-override.properties");
        propertyPlaceholderConfigurer.setLocations(resources);
        propertyPlaceholderConfigurer.setIgnoreResourceNotFound(true);
        propertyPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
        return propertyPlaceholderConfigurer;
    }

问题是当我将 Environment 注入另一个 bean 时,我的所有属性都不存在。

如下调用失败:

environment.getRequiredProperty("application.security.ldap.userSearchBase"

PropertyPlaceholderConfigurer 中的属性不应该在 Environment 中可用吗?

如果我执行以下操作,它确实有效,但我希望这些属性在环境中可用

@Value("${application.security.ldap.userSearchBase}")
private String userSearchBase;

注意:如果我使用 PropertySourcesPlaceholderConfigurer,也会发生同样的事情。

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    我们使用PropertySourcesPlaceholderConfigurer。据我了解,属性源是由这个专用的 spring bean 加载的。 PropertySourcesPlaceholderConfigurer 是一个 static bean,我们将其声明如下。

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){
      //return PropertySourcesPlaceholderConfigurer
    }
    
    • 首先创建这些静态 bean。
    • 它确保在初始化任何@Configuration bean 之前读取属性源。

    【讨论】:

      猜你喜欢
      • 2012-02-13
      • 2012-06-06
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      • 2016-06-26
      相关资源
      最近更新 更多