在Spring Boot项目中通过@ConfigurationProperties从YAML配置文件注入属性时,可能遇到注解失效的情况。以下整理几种常见原因及对应的解决思路,供开发者参考。

写了ConfigurationProperties但未配置Component,Component是必须的。
@Component @ConfigurationProperties(prefix = "")
实体类中字段被声明为静态,导致注入失效。例如下方代码中的name为static。
@Component
@ConfigurationProperties(prefix = "userinfo")
public class User
{
private static String name;
public static String getName()
{
return name;
}
public static void setName(String name)
{
this.name = name;
}
}
也就是我遇到的问题——使用实体类时未通过注解自动注入,而是直接new对象,导致属性为null。
//使用实体类的时候没有使用注解自动注入 User user = new User(); name = user.getName();//这样当然NullPointException
以上列举了@ConfigurationProperties注解失效的三种典型情况,排查时可对照检查定义方式与注入方法,以快速定位问题。
您可能感兴趣的文章: