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

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

    Beware of spaces in the values. I could be wrong, but I think spaces in the comma-separated list are not truncated using @Value and Spel. The list

    foobar=a, b, c
    

    would be read in as a list of strings

    "a", " b", " c"
    

    In most cases you would probably not want the spaces!

    The expression

    @Value("#{'${foobar}'.trim().replaceAll(\"\\s*(?=,)|(?<=,)\\s*\", \"\").split(',')}")
    private List foobarList;
    

    would give you a list of strings:

    "a", "b", "c".
    

    The regular expression removes all spaces just before and just after a comma. Spaces inside of the values are not removed. So

    foobar = AA, B B, CCC
    

    should result in values

    "AA", "B B", "CCC".
    

提交回复
热议问题