SpringBoot使用@ConfigurationProperties常见异常分析
在SpringBoot项目中使用@ConfigurationProperties注解进行配置文件绑定时往往会遇到两个问题:注释报错和IDE警告提示。
使用注释报错
以下面的示例代码,使用@ConfigurationProperties如下:
@Data // lombok注解
@ConfigurationProperties(prefix = "remote")
public class ServerProperties {
private String ip;
private String port;
}
会发现@ConfigurationProperties注解报如下错误:
Not registered via @EnableConfigurationProperties, marked as Spring component, or scanned via @ConfigurationPropertiesScan
为什么会报上面的错误?其实错误信息中已经很明确了。因为被注解的类没有进行实例化操作,比如没有使用@Component进行实例化操作。
修改之后如下:
@Data
@Component
@ConfigurationProperties(prefix = "remote")
public class ServerProperties {
private String ip;
private String port;
}
错误信息便消失了。
提示问题解决

但此时在IDEA的上面还会有对应的提示信息:
提示信息:
Spring Boot Configuration Annotation Processor not configured
点开右上角的“Open Documentation”,进入官方文档的配置说明。根据官网的建议第一步操作,pom文件中添加如下配置:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
添加依赖文件之后,提示信息变为如下:

提示已经变了,右上角也变为可以隐藏此提示消息了,点击隐藏即可。
但在官网还提示如果项目中定义了@ConfigurationProperties,还需要配置构建插件spring-boot-maven-plugin,用来阻止repackage的执行。
示例代码如下:
<project>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
经过以上步骤,使用@ConfigurationProperties场景异常变解决了。

关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台
除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接
本文链接:https://choupangxia.com/2020/11/26/springboot-configurationproperties/