【问题标题】:PropertySourcesPlaceholderConfigurer and SpEL?PropertySourcesPlaceholderConfigurer 和 SpEL?
【发布时间】:2016-07-19 13:13:35
【问题描述】:

由于我们相当复杂的properties 文件设置,我们不能简单地使用@PropertySource

这是属性文件:

connection.http.connectTimeout=15000
#connection.http.readTimeout=${connection.http.connectTimeout}
connection.http.readTimeout=#{30*1000}

第二行仍然有效,并将 readTimeout 设置为 15000,但在第三行到位后,该值仅为 0。

bean 类:

@Component
@ConfigurationProperties("connection")
public class ConnectionConfig {

  @NestedConfigurationProperty
  private ConnectionSourceConfig http;

  public ConnectionSourceConfig getHttp() {
    return http;
  }

  public void setHttp(ConnectionSourceConfig http) {
    this.http = http;
  }

}

public class ConnectionSourceConfig {

  private long connectTimeout;

  private long readTimeout;

  public long getConnectTimeout() {
    return connectTimeout;
  }

  public void setConnectTimeout(long connectTimeout) {
    this.connectTimeout = connectTimeout;
  }

  public long getReadTimeout() {
    return readTimeout;
  }

  public void setReadTimeout(long readTimeout) {
    this.readTimeout = readTimeout;
  }

}

使用 PropertySourcesPlaceholderConfigurer 似乎会阻止 SpEL 工作:

@Configuration
public class BaseAppConfig {

  @Bean
  public static PropertySourcesPlaceholderConfigurer properties(Environment environment) throws IOException {
    String env = getEnvProperty(environment);
    PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
    configurer.setLocations(getPropertiesFiles(env));
    configurer.setIgnoreResourceNotFound(true);
    return configurer;
  }

我尝试了更高级的PropertySourcesPlaceholderConfigurer,但从未调用过convertPropertyValue()

    PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer() {

      @Override
      protected String convertPropertyValue(String originalValue) {
        System.out.println("Parse " + originalValue);
        return super.convertPropertyValue(originalValue);
      }

    };

我试图研究 Spring 是如何工作的,它似乎与 PropertyResolvers 一起工作。但是,我不知道如何将其编织进去。

但是,也许我在 Spring 的处理生命周期方面犯了一个错误......

【问题讨论】:

    标签: java configuration spring-boot properties-file spring-el


    【解决方案1】:

    在属性文件方面,# 被视为注释块。这样做,您的属性文件最终会将属性设置为空。

    connection.http.readTimeout=#{30*1000}renders to connection.http.readTimeout= 因为# 之后的所有内容都被忽略了。

    【讨论】:

    • 天啊,这么简单的答案!我完全“忘记”了这一点。虽然说只是看看我的属性示例......它一直在那里......伟大的金发时刻............
    • 很高兴在如此困难的时刻提供帮助 :)
    猜你喜欢
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多