Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid truncating zero leading numbers when inserted with Spring's @Value annotation?

Let's say we have an environment variable exported as:

export SOME_STRING_CONFIG_PARAM="01"

and application.properties with:

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

injected to a Java field:

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

After booting the Spring application printing out the field:

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

results with:

someStringConfigParam: 1

How to tell Spring that the value should be treated as a String?

like image 382
Boris Pavlović Avatar asked Jun 16 '16 13:06

Boris Pavlović


1 Answers

I get the correct answer by your demo project:

This is the Test Property Value = 01

But I get the problem in yml file, the reason is yml treat 01 as integer by default. Just use double quotes to solve it.

Type examples in yml file:

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.

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

like image 74
bluearrow Avatar answered Jan 24 '23 15:01

bluearrow