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

最新下载

热门教程

@ConfigurationProperties及EnableConfigurationProperties使用与说明

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

@ConfigurationProperties注解负责把配置文件中的属性值映射到Java实体类,是实现配置注入的关键工具。本文通过实际案例,详细讲解其使用方法以及与@EnableConfigurationProperties的配合场景,帮助读者快速掌握两者的应用。

@ConfigurationProperties与EnableConfigurationProperties

首先需要理解@ConfigurationProperties注解的功能:它实现了配置文件和实体类之间的属性注入。

@ConfigurationProperties与EnableConfigurationProperties使用及说明

@ConfigurationProPerties注解完成了配置文件中数据向实体类字段的自动绑定。

举例说明

application.yml文件:

student:
  name: 小明

Student.java:

@ConfigurationProperties(prefix = "student")
public class Student {
    private String name;
    public Student() {
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

此处需留意:@ConfigurationProperties通常置于类上,它通过setter方法为成员变量赋值;若缺少setter,注入将无法成功。

除了类级别的@ConfigurationProPerties注解,还可以直接在成员变量上使用@Value("${ }")实现属性注入,而且这种方式无需提供setter方法。

此时的Student类有没有注入容器中呢?

如果容器中已存在Student类,利用Spring控制反转特性,注入进容器的Bean可以直接通过注解互相注入。

@Configuration
public class Myconfig {
    @Autowired
    private Student student;
    public void  sout(){
        System.out.println(student.getName()+"****");
    }
}

运行后控制台报错:student不满足依赖关系,即容器中找不到该Bean。

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myconfig': Unsatisfied dependency expressed through field 'student';​

既然Student未被注入容器,那在Student类上添加@Component注解即可解决问题,这自然是可行的。

接下来上代码

这里采用属性注入的另一种方式:

@Component
public class Student {
    @Value("${student.name}")
    private String name;
    public Student() {
    }
    public String getName() {
        return name;
    }
}

配置类不做改变

@Configuration
public class Myconfig {
    @Autowired
    private Student student;
    public void  sout(){
        System.out.println(student.getName()+"****");
    }
}

这一次,控制台成功打印信息:

小明****​

但通常不会直接在实体类上添加@Component注解,具体原因暂且不表。

如果不使用@Component,那么如何在配置类Myconfig中获取Student类中的属性值呢?此时@EnableConfigurationProperties注解便派上了用场。

student这个类

需要往哪个Bean中注入,就在哪个类的上方添加@EnableConfigurationProperties注解。

@EnableConfigurationProperties({com.example.pojo.Student.class})
@Configuration
public class Myconfig {
    @Autowired
    private Student student;
    public void  sout(){
        System.out.println(student.getName()+"****");
    }
}

结果正确无误。

小明****

需要特别说明:@EnableConfigurationProperties无法单独使用,它必须指定一个值——即声明了@ConfigurationProperties注解的类的全限定类名。

总结

通过上述实例可以看出,@ConfigurationProperties依赖setter方法完成属性注入,也可用@Value替代;若不希望在实体类上添加@Component,则可通过@EnableConfigurationProperties将该配置类注入容器,从而实现解耦与灵活配置。

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

热门栏目