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

前端 未结 16 1364
陌清茗
陌清茗 2020-11-22 14:01

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

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

And to load it in my class directly, ie:

相关标签:
16条回答
  • 2020-11-22 14:37

    If you are using Spring Boot 2, it works as is, without any additional configuration.

    my.list.of.strings=ABC,CDE,EFG
    
    @Value("${my.list.of.strings}")
    private List<String> myList;
    
    0 讨论(0)
  • 2020-11-22 14:37

    In my case of a list of integers works this:

    @Value("#{${my.list.of.integers}}")
    private List<Integer> listOfIntegers;
    

    Property file:

    my.list.of.integers={100,200,300,400,999}
    
    0 讨论(0)
  • 2020-11-22 14:42

    Consider using Commons Configuration. It have built in feature to break an entry in properties file to array/list. Combing with SpEL and @Value should give what you want


    As requested, here is what you need (Haven't really tried the code, may got some typoes, please bear with me):

    In Apache Commons Configuration, there is PropertiesConfiguration. It supports the feature of converting delimited string to array/list.

    For example, if you have a properties file

    #Foo.properties
    foo=bar1, bar2, bar3
    

    With the below code:

    PropertiesConfiguration config = new PropertiesConfiguration("Foo.properties");
    String[] values = config.getStringArray("foo");
    

    will give you a string array of ["bar1", "bar2", "bar3"]

    To use with Spring, have this in your app context xml:

    <bean id="fooConfig" class="org.apache.commons.configuration.PropertiesConfiguration">
        <constructor-arg type="java.lang.String" value="classpath:/Foo.properties"/>
    </bean>
    

    and have this in your spring bean:

    public class SomeBean {
    
        @Value("fooConfig.getStringArray('foo')")
        private String[] fooArray;
    }
    

    I believe this should work :P

    0 讨论(0)
  • 2020-11-22 14:44

    I think this is simpler for grabbing the array and stripping spaces:

    @Value("#{'${my.array}'.replace(' ', '').split(',')}")
    private List<String> array;
    
    0 讨论(0)
提交回复
热议问题