使用Spring的@Value注释插入时如何避免截断零前导数?

时间:2016-06-16 13:23:04

标签: java spring spring-boot annotations

我们假设我们将环境变量导出为:

export SOME_STRING_CONFIG_PARAM="01"

application.properties

some.string.config.param=${SOME_STRING_CONFIG_PARAM:01}

注入Java字段:

@Value("${some.string.config.param}")
String someStringConfigfParam;

启动Spring应用程序后打印出字段:

System.out.println("someStringConfigParam: " + someStringConfigParam);

结果:

someStringConfigParam: 1

如何告诉Spring该值应该被视为String?

1 个答案:

答案 0 :(得分:2)

我的演示项目得到了正确答案:

This is the Test Property Value = 01

但我在yml文件中遇到问题,原因是yml默认情况下将01视为整数。只需使用双引号即可解决问题。

yml文件中输入示例:

a: 123                     # an integer
b: "123"                   # a string, disambiguated by quotes
c: 123.0                   # a float
d: !!float 123             # also a float via explicit data type prefixed by (!!)
e: !!str 123               # a string, disambiguated by explicit type
f: !!str Yes               # a string via explicit type
g: Yes                     # a boolean True (yaml1.1), string "Yes" (yaml1.2)
h: Yes we have No bananas  # a string, "Yes" and "No" disambiguated by context.

另见: https://en.wikipedia.org/wiki/YAML
Do I need quotes for strings in Yaml?