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

前端 未结 16 1522
陌清茗
陌清茗 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:27

    Since Spring 3.0, you can add a line like

    
    

    to your applicationContext.xml (or where you configure things). As Dmitry Chornyi points out in a comment, Java based configuration looks like:

    @Bean public ConversionService conversionService() {
        return new DefaultConversionService();
    }
    

    This activates the new configuration service which supports converting String to Collection types. If you do not activate this configuration service, Spring falls back on its legacy property editors as configuration services, which do not support this kind of conversion.

    Converting to collections of other types works, too:

    @Value("${my.list.of.ints}")
    private List myList
    

    will work with a line like

     my.list.of.ints= 1, 2, 3, 4
    

    No problems with whitespace there, the ConversionServiceFactoryBean takes care of it.

    See http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#core-convert-Spring-config

    In a Spring application, you typically configure a ConversionService instance per Spring container (or ApplicationContext). That ConversionService will be picked up by Spring and then used whenever a type conversion needs to be performed by the framework. [...] If no ConversionService is registered with Spring, the original PropertyEditor-based system is used.

提交回复
热议问题