如何预处理来自 spring 配置文件的值?

How to pre-process values from spring configuration file?

我有一个配置参数 "myconfig.defaultSize",其值在 application.properties 文件中被定义为“10MB”。

另一方面,我有一个 @Component class 和 @ConfigurationProperties 注释映射那些配置参数,如下所示。

@Component
@ConfigurationProperties(prefix="myconfig")
public class StorageServiceProperties {
   private Long defaultSize;
   //...getters and setters
}

那么,我该如何应用一种方法将 String 值转换为 Long?

public void setDefaultSize(String defaultSize) {
  try {
    this.defaultSize = Long.valueOf(defaultSize);
  } catch (NumberFormatException e) {
    // handle the exception however you like
  }
}

您不能在 属性 到 属性 的基础上应用此类通用转换器。您可以注册一个从 String 到 Long 的转换器,但在每种情况下都会调用它(基本上是 Long 类型的任何 属性)。

@ConfigurationProperties的目的是将Environment映射到更高级别的数据结构。也许你可以在那里做?

@ConfigurationProperties(prefix="myconfig")
public class StorageServiceProperties {
    private String defaultSize;
    // getters and setters

    public Long determineDefaultSizeInBytes() {
        // parsing logic
    }

}

如果您查看 Spring Boot 中的多部分支持,我们 keep the String value and we use the @ConfigurationProperties object 创建一个 MultipartConfigElement 负责解析。这样您就可以在代码和配置中指定那些特殊值。