In my Spring Boot application, I have a properties file with the following property:
my.application.property=something, something else, yet another something, something,which,must,remain,whole,no,splitting,allowed
What I need to do is get the property as a list/array (no problem there), however, the last property must not be split on commas. In other words, I would end up with this after injecting the values:
String[] myProps = {
[0] => "something",
[1] => "something else",
[2] => "yet another something",
[3] => "something,which,must,remain,whole,no,splitting,allowed"
}
What I’ve tried:
- Escaping the commas with backslashes (
,
) and double backslashes (\,
) - Enclosing the value in double quotes (
""
), curly braces ({}
) and brackets ([]
) - Moving the value to a separate property, then using that,
e.g.,
other.prop="something,which,must,remain,whole,no,splitting,allowed"
my.application.property=..., ${other.prop}
How can I get Spring Boot to ignore commas just this once?
As mentioned in the comment by @JavaSheriff, there seems to be no escaping the no-escaping of commas. So I did a hacky little workaround, by taking advantage of Spring’s @PostConstruct
annotation, like so:
// the field into which I want to inject values
@Value("${my.application.property}")
private List<String> props;
// an extra field to hold the comma-containing value
@Value("${other.prop}")
private List<String> otherProps;
@PostContruct
private void fixArgs() {
// re-constitute values with commas
String collectedArgs = String.join(",", otherProps);
props.add(collectedArgs);
}
The @PostConstruct
annotation causes the method to be run after the bean has been instantiated and the values injected.
I found this, let me know if it helps
Custom separator for list properties
By default, Spring splits your property by the comma. There is no way to escape comma. What should you do if you want another separator like the semicolon?
1
sbpg.init.numbers=0;1;1;2;3;5;8
Fortunately, you can split the property on your own using a different separator. All you need is a simple expression.
1
2
3
4
InitService(@Value("#{'${sbpg.init.numbers}'.split(';')}")
List<Integer> numbers) {
// ...
}
What is going on here?
Spring injects the property as a regular string. You indicate it with the single quotations marks. Next, inside the expression (#{…}), the split() method of the String class is called on the injected value. Finally, Spring puts the result into the list.
Alternatively, you can inject the property as a regular string and split it on your own. You should decide what is more readable for you.