2016-12-28 23 views
0

我有一个配置参数“myconfig.defaultSize”,其值在application.properties文件中定义为例如“10MB”。如何预先处理来自spring配置文件的值?

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

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

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

回答

1

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

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

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

    public Long determineDefaultSizeInBytes() { 
     // parsing logic 
    } 

} 

如果你看一下在春季启动了多支持,我们keep the String value and we use the @ConfigurationProperties object创建MultipartConfigElement,负责解析的。这样你可以在代码和配置中指定这些特殊值。

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