我想将嵌套的 List 属性加载到 JAVA POJO
我正在使用类 A 上的 ConfigurationProperties
注释从 yml 加载属性。我的列表是 B 类型。这个 B 对象有自己的 LIST 属性。但是 yml 属性没有按预期加载。
@ConfigurationProperties(prefix="prop")
public class A{
List<B> b = new ArrayList<>();
//getters and setters ......
}
public class B{
String user; //This property gets loaded.
List<String> list = new ArrayList<>(); //However this list is still empty
//getters and setters ......
}
我在 application.yml
中的属性如下所示。
prop:
-
user: alpha
list: a,b,c
-
user: beta
list: x,y,z
最佳答案
这不是列表的 YAML 语法:
列表:a、b、c
这只是一个字符串a,b,c
。
如果您想使用逗号分隔列表,可以在加载后对其进行解析。
Spring 对它自己的一些属性做了类似的事情,就像本例中的 RabbitMQ 属性一样。 地址
以逗号分隔,函数parseAddresses()
在加载后分割字符串,作为该成员的setter方法的一部分。
否则使用 YAML 列表语法。
prop:
- user: alpha
list:
- a
- b
- c
- user: beta
list:
- x
- y
- z
关于java - 将列表类型属性从应用程序 yml 加载到 Java POJO 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54824439/