具有特定值解析器的 PropertySourcesPlaceholderConfigurer

PropertySourcesPlaceholderConfigurer With Specific Value Parser

我知道 ${...}-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 是如何工作的,它似乎与 PropertyResolver 一起工作。但是,我不知道如何将其编织到其中。

那我该如何解决呢?

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

几分钟之内,我就编写了一个奇特的持续时间配置,例如

connection.connectTimeout=${duration:15s}

缺少的link则为:

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