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

Bor*_*vić 6 java spring annotations spring-boot

假设我们有一个环境变量导出为:

export SOME_STRING_CONFIG_PARAM="01"
Run Code Online (Sandbox Code Playgroud)

application.properties与:

some.string.config.param=${SOME_STRING_CONFIG_PARAM:01}
Run Code Online (Sandbox Code Playgroud)

注入 Java 字段:

@Value("${some.string.config.param}")
String someStringConfigfParam;
Run Code Online (Sandbox Code Playgroud)

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

System.out.println("someStringConfigParam: " + someStringConfigParam);
Run Code Online (Sandbox Code Playgroud)

结果为:

someStringConfigParam: 1
Run Code Online (Sandbox Code Playgroud)

如何告诉 Spring 该值应该被视为字符串?

blu*_*row 7

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

This is the Test Property Value = 01
Run Code Online (Sandbox Code Playgroud)

但我在文件中遇到问题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.
Run Code Online (Sandbox Code Playgroud)

另请参阅: https: //en.wikipedia.org/wiki/YAML
我是否需要为 Yaml 中的字符串添加引号?