【问题标题】:PropertySourcesPlaceholderConfigurer With Specific Value Parser具有特定值解析器的 PropertySourcesPlaceholderConfigurer
【发布时间】:2016-07-20 19:52:49
【问题描述】:

我知道${...}-notation 只要包含对其他属性的引用就可以工作。但是,我想扩展该解析算法。

这是属性文件:

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

第二行仍然可以工作并将readTimeout 设置为 15000,但我想让第 3 行工作。我不得不说我不在乎我使用什么前缀和后缀,上面的例子使用了%{...},但不管怎样让它工作对我来说都很好。 ${...} 可能是更好的选择,因为所有必需的解析都已经存在,但是我的新算法必须在通常的 Spring-stuff 之前启动。

这是我目前所拥有的:

@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 一起工作。但是,我不明白我怎么能把它织进去。

那我该如何解决呢?

【问题讨论】:

    标签: java spring configuration properties-file


    【解决方案1】:

    实际上,一旦我知道Spring's RandomValuePropertySource 完全按照我的预期工作,这很容易。

    几分钟之内,我就可以编写一个花哨的持续时间配置,例如

    connection.connectTimeout=${duration:15s}
    

    那么缺少的链接是:

      @Bean
      public static PropertySourcesPlaceholderConfigurer properties(Environment environment) throws IOException {
        AbstractEnvironment standardEnvironment = ((AbstractEnvironment) environment);
        MutablePropertySources propertySources = standardEnvironment.getPropertySources();
        propertySources.addLast(new DurationValuePropertySource());
      }
    

    【讨论】:

      猜你喜欢
      • 2023-02-07
      • 2021-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多