解决springboot不能解析@ConfigurationProperties(prefix = “xxx“)

问题场景:

项目中使用@ConfigurationProperties初始化一个配置类,始终无法初始化成功,按照官网方文档和百度的步骤,添加pom,仔细修改yaml文件,结果还是无法初始化。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

官网链接:https://docs.spring.io/spring-boot/docs/2.4.4/reference/html/appendix-configuration-metadata.html#configuration-metadata-annotation-processor-metadata-generation
完整一些的博客资料:https://blog.csdn.net/weixin_43290126/article/details/107616875


问题解决:

找了一个能正常初始化Bean的类,仔细对比,发现了少了无参构造函数,加上就能正常初始化。
下面这个官网的实例,完全没有提示要求有无参构造函数。

@ConfigurationProperties(prefix="server")
public class ServerProperties {

    /**
    * Name of the server.
    */
    private String name;

    /**
     * IP address to listen to.
     */
    private String ip = "127.0.0.1";

    /**
    * Port to listener to.
    */
    private int port = 9797;

    // ... getter and setters

}
ont>

在上面的代码中,加上构造函数即可:

	public ServerProperties () {
    }

上一篇:php中abstract的用法


下一篇:Java获取本机IP地址(屏蔽无用地址)