@ConfigurationProperties 是 Spring Boot 中的标签,它可以让开发者将整个配置文件,映射到对象中,比@Value 效率更高。
通常,它可以和@PropertySource 标注一起使用,映射整个配置文件。
演示一个例子
ConfigurationProperties 演示代码
@Component
@PropertySource("classpath:my.properties")
@ConfigurationProperties(prefix = "user")
public class MyConfig {
private String username;
private int age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "username=" + username + ",age=" + age;
}
}
配置文件
my.properties
user.username=zhangsan user.age=20
调用该类
@RestController
@RequestMapping("/api")
public class Index {
@Autowired
MyConfig myconfig;
@GetMapping("/index")
public Object getStateStatistics() {
Map<String,String> m=new HashMap<>();
m.put("status", myconfig.toString());
return m;
}
}
@ConfigurationProperties 能支持 properties 文件和 yml 文件,并且支持更复杂配置结构以及 Validation 功能。
此处不做演示,可以参考 demo。
https://www.mkyong.com/spring-boot/spring-boot-configurationproperties-example/