javaspringspring-properties

Reading a List from properties file and load with Spring annotation @Value


I want to have a list of values in a .properties file, i.e.:

my.list.of.strings=ABC,CDE,EFG

And to load it in my class directly, i.e.:

@Value("${my.list.of.strings}")
private List<String> myList;

As I understand, an alternative of doing this is to have it in the Spring config file, and load it as a bean reference (correct me if I'm wrong), i.e.

<bean name="list">
 <list>
  <value>ABC</value>
  <value>CDE</value>
  <value>EFG</value>
 </list>
</bean>

But is there any way of doing this using a .properties file?

P.S.

I would like to do this without any custom code if possible.


Solution

  • Using Spring EL:

    @Value("#{'${my.list.of.strings}'.split(',')}") 
    private List<String> myList;
    

    Assuming your properties file is loaded correctly with the following:

    my.list.of.strings=ABC,CDE,EFG