【问题标题】:How to pre-process values from spring configuration file?如何预处理弹簧配置文件中的值?
【发布时间】:2017-05-12 20:31:18
【问题描述】:

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

另一方面,我有一个带有@ConfigurationProperties 注解的@Component 类映射这些配置参数,如下所示。

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

那么,我怎样才能应用一种方法将 String 值转换为 Long?

【问题讨论】:

    标签: java spring spring-boot configuration-files


    【解决方案1】:
    public void setDefaultSize(String defaultSize) {
      try {
        this.defaultSize = Long.valueOf(defaultSize);
      } catch (NumberFormatException e) {
        // handle the exception however you like
      }
    }
    

    【讨论】:

      【解决方案2】:

      您不能在属性到属性的基础上应用这种通用转换器。您可以注册一个从 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。这样您就可以在代码和配置中指定这些特殊值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-09
        • 2014-10-14
        • 2013-02-22
        • 2012-11-02
        • 2021-06-27
        相关资源
        最近更新 更多