Is there a way to set an empty list as default value for a property in Spring, something like:
@Value("${my.list.of.strings :" + new ArrayList<>() + "}")
private List<String> myList;
Obviously not new ArrayList, but I need an empty list there instead.
To set a default value for primitive types such as boolean and int, we use the literal value: @Value("${some. key:true}") private boolean booleanWithDefaultValue; @Value("${some.
By default, @RequestParam requires query parameters to be present in the URI. However, you can make it optional by setting @RequestParam 's required attribute to false . In the above example, the since query param is optional: @RequestParam(value="since", required=false) ).
Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. Spring @Value annotation also supports SpEL.
No, this is not (directly) possible. The default value of an annotation property must be a compile-time constant.
After taking a look at SpEL specification and combined with @javaguy's answer I came up with this:
@Value("${my.list.of.strings:}#{T(java.util.Collections).emptyList()}")
private List<String> myList;
Actually, in the current Spring versions works just one symbol :
with an empty default
value.
The full example that I'm using:
@Value("${my.custom.prop.array:}")
private List<Integer> myList;
To be sure and safer I also adding init to the List variable:
@Value("${my.custom.prop.array:}")
private List<Integer> myList = new ArrayList<>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With