记录@ConfigurationProperties注解注入集合配置的报错

记录@ConfigurationProperties注解注入集合配置的报错

分析

现象:项目中使用@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(){}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值