【问题标题】:How to avoid truncating zero leading numbers when inserted with Spring's @Value annotation?使用 Spring 的 @Value 注释插入时如何避免截断前导零数字?
【发布时间】:2016-10-18 01:16:52
【问题描述】:

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

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 该值应该被视为一个字符串?

【问题讨论】:

  • 您使用的是哪个版本的 Spring Boot?
  • 版本 1.2.7.RELEASE
  • yml 文件还是properties
  • 默认application.properties文件。
  • @BorisPavlović 我无法重现此问题。查看我使用 Spring Boot 1.2.7 github.com/kanderson450/stackoverflow-q37860589 的示例项目在此示例中,该属性没有被截断。

标签: java spring spring-boot annotations


【解决方案1】:

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

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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    相关资源
    最近更新 更多