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

@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类,利用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注解便派上了用场。
需要往哪个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将该配置类注入容器,从而实现解耦与灵活配置。
您可能感兴趣的文章: