无法在Spring启动应用程序中从yaml读取复杂属性。这是不同的部分
spring:
profiles: dev
test: BLAHSSD
serversList:
- host: localhost
port: 27017
db: myDB
username: xxx
password: yyy
Server.java
public class Server {
String host;
int port;
String db;
String username;
String password;
public Server() {
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getDb() {
return db;
}
public void setDb(String db) {
this.db = db;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Server [host=" + host + ", port=" + port + ", db=" + db + ", username=" + username + ", password="
+ password + "]";
}
}
Configuaration Reader
@Component
@Configuration
@PropertySource("file:/tmp/test.yaml")
@ConfigurationProperties()
public class TestDBConfiguration {
private String test;
private List<Server> serversList;
public List<Server> getServersList() {
return serversList;
}
public void setServersList(List<Server> serversList) {
this.serversList = serversList;
}
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
我能够阅读&#39;测试&#39;我评论serversList属性时的属性。但是继续为serverList获取此异常:
原因:无法转换类型&#39; java.lang.String&#39;的属性值至 必需的类型&#39; java.util.List&#39;对于属性&#39; serversList&#39;
答案 0 :(得分:1)
我相信你的yaml结构是无效的。尝试将其更改为:
spring:
profiles: dev
test: BLAHSSD
serversList:
- server:
host: localhost
port: 27017
db: myDB
username: xxx
password: yyy
答案 1 :(得分:0)
来自docs:
24.6.4 YAML缺点
无法通过
@PropertySource
注释加载YAML文件。所以 如果您需要以这种方式加载值,则需要使用a 属性文件。
此外,Java erases generics information at compile time。因此,在运行时,Spring将serverList
的类型视为List
,而不是List<Server>
,并且它无法将您的配置属性转换为Server
个对象的列表。