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

前端 未结 16 1520
陌清茗
陌清茗 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 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.

提交回复
热议问题