如何通过修改Spring @Value注解为List类型配置设置默认值
Absolutely, you can achieve this directly with a modified @Value annotation using Spring Expression Language (SpEL) to handle both missing configurations and empty values, while keeping your existing comma-separated format intact. Here are the exact implementations you need:
Option 1: Default to an Empty List
This will give you an empty List<String> when myapp.values is missing or has an empty value (e.g., myapp.values=):
@Value("#{'${myapp.values:}'.isEmpty() ? T(java.util.Collections).emptyList() : '${myapp.values:}'.split(',')}") private List<String> values;
Breakdown:
${myapp.values:}: The colon:sets a default empty string when the property doesn't exist or is explicitly empty.- SpEL conditional check: If the resulting string is empty, we return
Collections.emptyList()(an immutable empty list). Otherwise, we split the string by commas into a list.
If you prefer a mutable empty list instead, replace T(java.util.Collections).emptyList() with new java.util.ArrayList<>() (note the fully qualified class name required in SpEL).
Option 2: Default to Null
If you want the list to be null instead of an empty list when the property is missing/empty, adjust the conditional to return null:
@Value("#{'${myapp.values:}'.isEmpty() ? null : '${myapp.values:}'.split(',')}") private List<String> values;
Handling Edge Cases (Optional)
If your configuration might contain empty entries (e.g., myapp.values=value1,,value3) and you want to retain those empty strings in the list, the above code will work as-is. If you want to filter out empty entries automatically, extend the SpEL expression to include a stream filter:
@Value("#{T(java.util.Arrays).asList('${myapp.values:}'.split(',')).stream().filter(s -> !s.trim().isEmpty()).collect(T(java.util.stream.Collectors).toList())}") private List<String> values;
This will remove any blank strings (including those with just whitespace) from the resulting list.
All these solutions strictly use the @Value annotation as you requested, no alternative approaches like @ConfigurationProperties are involved.
内容的提问来源于stack exchange,提问作者Rinkashikachi

