春天@Value标注不使用默认值时,属性不是present [英] Spring @Value annotation not using defaults when property is not present

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

问题描述

我想在构造函数的参数使用@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) {
...
}

在属性文件在类路径present,性质是完全加载和执行测试罚款。然而,当我删除的属性从classpath文件,我本来预计会被使用的默认值,例如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.

通过一个调试运行code(这只会改变后的 @Value($ {encryptor.poolSize:10}工作)整数poolSize @Value($ {encryptor.poolSize:10})字符串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!

感谢您

推荐答案

属性占位符配置器也许初始化失败由于错过属性文件,使占位符都没有解决。你可以配置它忽略丢失的文件如下(如果你使用背景命名空间配置):

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" ... />

你也不必...周围的默认值。

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

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