Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Value empty list as default

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.

like image 981
Andrei Roba Avatar asked Mar 21 '17 07:03

Andrei Roba


People also ask

How do I set default value in spring?

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.

How do I set default value in RequestParam?

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) ).

What is @value annotation in spring?

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.

Can I use @value in interface?

No, this is not (directly) possible. The default value of an annotation property must be a compile-time constant.


2 Answers

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;
like image 95
Andrei Roba Avatar answered Oct 16 '22 15:10

Andrei Roba


Actually, in the current Spring versions works just one symbol : with an empty defaultvalue.

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<>();
like image 18
sf_ Avatar answered Oct 16 '22 14:10

sf_