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

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

    Have you considered @Autowireding the constructor or a setter and String.split()ing in the body?

    class MyClass {
        private List<String> myList;
    
        @Autowired
        public MyClass(@Value("${my.list.of.strings}") final String strs) {
            myList = Arrays.asList(strs.split(","));
        }
    
        //or
    
        @Autowired
        public void setMyList(@Value("${my.list.of.strings}") final String strs) {
            myList = Arrays.asList(strs.split(","));
        }
    }
    

    I tend to prefer doing my autowiring in one of these ways to enhance the testability of my code.

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

    Since Spring 3.0, you can add a line like

    <bean id="conversionService" 
        class="org.springframework.context.support.ConversionServiceFactoryBean" />
    

    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<Integer> 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.

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

    All the above answers are correct. But you can achieve this in just one line. Please try following declaration and you will get all the comma separated values in a String list.

    private @Value("#{T(java.util.Arrays).asList(projectProperties['my.list.of.strings'])}") List<String> myList;
    

    And also you need to have the following line defined in your xml configuration.

    <util:properties id="projectProperties" location="/project.properties"/>
    

    just replace the path and file name of your properties file. And you are good to go. :)

    Hope this helps you. Cheers.

    0 讨论(0)
  • 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<String> 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.

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

    I am using Spring Boot 2.2.6

    My property file:

    usa.big.banks= JP Morgan, Wells Fargo, Citigroup, Morgan Stanley, Goldman Sachs
    

    My code:

    @Value("${usa.big.banks}")
        private List<String> bigBanks;
    
    @RequestMapping("/bigbanks")
        public String getBanks() {
            System.out.println("bigBanks = " + bigBanks);
            return bigBanks.toString();
        }
    

    It works fine

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

    you can do this with annotations like this

     @Value("#{T(java.util.Arrays).asList('${my.list.of.strings:a,b,c}')}") 
        private List<String> mylist;
    

    here my.list.of.strings will be picked from the properties file, if its not there, then the defaults a,b,c will be used

    and in your properties file, you can have something like this

    my.list.of.strings=d,e,f

    0 讨论(0)
提交回复
热议问题