一聚教程网:一个值得你收藏的教程网站

热门教程

@ConfigurationProperties(prefix="")不起作用问题及解决方案

时间:2026-06-04 08:26:25 编辑:袖梨 来源:一聚教程网

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

@ConfigurationProperties(prefix=“”)不起作用

@ConfigurationProperties(prefix=“”)不起作用问题及解决方案

第一种

写了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注解失效的三种典型情况,排查时可对照检查定义方式与注入方法,以快速定位问题。

您可能感兴趣的文章:
  1. @ConfigurationProperties与EnableConfigurationProperties使用及说明
  2. @ConfigurationProperties注解原理与实践方式
  3. @ConfigurationProperties用法及说明
  4. 深入解析Spring Boot中的@ConfigurationProperties注解
  5. @ConfigurationProperties及@NestedConfigurationProperty的使用解读
  6. 将SpringBoot属性配置类@ConfigurationProperties注册为Bean的操作方法
  7. SpringBoot @ConfigurationProperties + Validation实现启动期校验解决方案

热门栏目