Spring Boot:不要在属性文件中以逗号分隔

问题描述 投票:0回答:1

在我的 Spring Boot 应用程序中,我有一个具有以下属性的属性文件:

my.application.property=something, something else, yet another something, something,which,must,remain,whole,no,splitting,allowed

我需要做的是以列表/数组的形式获取属性(没有问题),但是,最后一个属性不能用逗号分割。换句话说,在注入值后我会得到这样的结果:

String[] myProps = {
  [0] => "something",
  [1] => "something else",
  [2] => "yet another something",
  [3] => "something,which,must,remain,whole,no,splitting,allowed"
}

我尝试过的

  • 使用反斜杠 (
    \,
    ) 和双反斜杠 (
    \\,
    ) 转义逗号
  • 将值括在双引号 (
    ""
    )、大括号 (
    {}
    ) 和中括号 (
    []
    ) 中
  • 将值移动到单独的属性,然后使用它,

例如,

other.prop="something,which,must,remain,whole,no,splitting,allowed"
my.application.property=..., ${other.prop}

如何让 Spring Boot 忽略逗号这一次?

spring spring-boot properties-file value-initialization
1个回答
0
投票

我找到了这个,如果有帮助请告诉我

Custom separator for list properties

By default, Spring splits your property by the comma. There is no way to escape comma. What should you do if you want another separator like the semicolon?
1
    
sbpg.init.numbers=0;1;1;2;3;5;8

Fortunately, you can split the property on your own using a different separator. All you need is a simple expression.
1
2
3
4
    
InitService(@Value("#{'${sbpg.init.numbers}'.split(';')}") 
            List<Integer> numbers) {
   // ...
}

What is going on here?

Spring injects the property as a regular string. You indicate it with the single quotations marks. Next,  inside the expression (#{…}), the split() method of the String class is called on the injected value. Finally, Spring puts the result into the list.

Alternatively, you can inject the property as a regular string and split it on your own. You should decide what is more readable for you.
© www.soinside.com 2019 - 2024. All rights reserved.