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

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

    If you are using latest Spring framework version(Spring 3.1+ I believe), you don't need to those string split stuff in SpringEL,

    Simply add PropertySourcesPlaceholderConfigurer and DefaultConversionService in your Spring's Configuration class ( the one with annotated with Configuration ) e.g,

    @Configuration
    public class AppConfiguration {
    
        @Bean
        public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
            return new PropertySourcesPlaceholderConfigurer();
        }
    
        @Bean public ConversionService conversionService() {
            return new DefaultConversionService();
        }
    }
    

    and in your class

    @Value("${list}")
    private List list;
    

    and in the properties file

    list=A,B,C,D,E
    

    Without DefaultConversionService, you can only take comma separated String into String array when you inject the value into your field, but DefaultConversionService does a few convenient magic for you and will add those into Collection, Array, etc. ( check the implementation if you'd like to know more about it )

    With these two, it even handles all the redundant whitespaces including newline, so you don't need to add additional logics to trim them.

提交回复
热议问题