当属性不存在时,Spring @Value 注释不使用默认值 [英] Spring @Value annotation not using defaults when property is not present

查看:46
本文介绍了当属性不存在时,Spring @Value 注释不使用默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在构造函数的参数中使用 @Value 注释,如下所示:

I am trying to use @Value annotation in the parameters of a constructor as follows:

@Autowired
public StringEncryptor(
    @Value("${encryptor.password:\"\"}") String password,
    @Value("${encryptor.algorithm:\"PBEWithMD5AndTripleDES\"}") String algorithm,
    @Value("${encryptor.poolSize:10}") Integer poolSize, 
    @Value("${encryptor.salt:\"\"}") String salt) {
...
}

当类路径上存在属性文件时,属性被完美加载并且测试执行正常.但是,当我从类路径中删除属性文件时,我预计会使用默认值,例如 poolSize 将设置为 10 或算法为 PBEWithMD5AndTripleDES 但情况并非如此.

When the properties file is present on the classpath, the properties are loaded perfectly and the test executes fine. However when I remove the properties file from the classpath, I would have expected that the default values would have been used, for example poolSize would be set to 10 or algorithm to PBEWithMD5AndTripleDES however this is not the case.

通过调试器运行代码(只有在将 @Value("${encryptor.poolSize:10}") Integer poolSize 更改为 @Value("${encryptor.poolSize:10}") String poolSize 因为它导致了 NumberFormatExceptions)我发现没有设置默认值并且参数的形式为:

Running the code through a debugger (which would only work after changing @Value("${encryptor.poolSize:10}") Integer poolSize to @Value("${encryptor.poolSize:10}") String poolSize as it was causing NumberFormatExceptions) I find that the defaults are not being set and the parameters are in the form of:

poolSize = ${encryptor.poolSize:10}

algorithm = ${encryptor.algorithm:"PBEWithMD5AndTripleDES"}

不如预期

poolSize = 10

algorithm = "PBEWithMD5AndTripleDES"

基于 SPR-4785 表示法,例如 ${my.property:myDefaultValue} 应该管用.但它不会发生在我身上!

Based on SPR-4785 the notation such as ${my.property:myDefaultValue} should work. Yet it's not happening for me!

谢谢

推荐答案

可能是由于缺少属性文件导致属性占位符配置器初始化失败,从而导致占位符未解析.您可以将其配置为忽略丢失的文件,如下所示(如果您使用 context 命名空间来配置它):

Perhaps initialization of property placeholder configurer fails due to missed properties file, so that placeholders are not resolved. You can configure it to ignore missed files as follows (if you use context namespace to configure it):

<context:property-placeholder ignore-resource-not-found="true" ... />

此外,您不需要 "..." 围绕默认值.

Also you don't need "..." around default values.

这篇关于当属性不存在时,Spring @Value 注释不使用默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆