分析
现象:项目中使用@ConfigurationProperties(prefix = “xxx”)注入配置类中存在集合成员变量时,项目启动报错
分析:网上查到都说yml配置存在空格的问题,但是本人项目是使用的properties文件,所以排除,在本地写测试代码复现这个报错,启动项目报错如下
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2023-03-28 18:00:03.559 ERROR 14660 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Binding to target [Bindable@5b44318 type = java.util.List<com.tcxm.panda.demo.controller.HostConfig>, value = 'provided', annotations = array<Annotation>[[empty]]] failed:
Property: test.host[0].charset
Value: UTF-8
Origin: class path resource [application.properties] - 4:24
Reason: The elements [test.host[0].charset,test.host[0].desc,test.host[0].ip,test.host[0].port] were left unbound.
Property: test.host[0].desc
Value: desc...
Origin: class path resource [application.properties] - 3:21
Reason: The elements [test.host[0].charset,test.host[0].desc,test.host[0].ip,test.host[0].port] were left unbound.
Property: test.host[0].ip
Value: 127.0.0.1
Origin: class path resource [application.properties] - 1:19
Reason: The elements [test.host[0].charset,test.host[0].desc,test.host[0].ip,test.host[0].port] were left unbound.
Property: test.host[0].port
Value: 8080
Origin: class path resource [application.properties] - 2:21
Reason: The elements [test.host[0].charset,test.host[0].desc,test.host[0].ip,test.host[0].port] were left unbound.
Action:
Update your application's configuration
下面贴一下我的配置类代码
application.properties
...
test.host[0].ip = 127.0.01
test.host[0].port = 8080
test.host[0].desc = desc...
test.host[0].charset = UTF-8
...
TestConfig.java
@Data
@Component
@ConfigurationProperties(prefix = "test")
public class TestConfig {
private List<HostConfig> host;
...
}
HostConfig.java
@Data
public class HostConfig {
private String ip;
private String port;
private String desc;
private String charset;
public HostConfig(String ip, String port, String desc, String charset) {
this.ip = ip;
this.port = port;
this.desc = desc;
this.charset = charset;
}
}
总结
在HostConfig类中由于重写了构造方法,默认的无参构造就不存在了,spring容器启动时实例化配置类的成员变量是调用的无参构造方法,这里初始化就会报错,如果是配置文件注入的话可以指定spring初始化时调用有参的构造方法<constructor-arg>
,但这里使用了注解注入,所以一定要注意保留无参构造来保证spring容器初始化成功
//在HostConfig.java新增无参构造后可以启动成功
public HostConfig(){}