上篇文章讲到 Spring Boot 2.2.0 和 MyBatis 兼容问题 ,今天再来看一下 这个 boom change
如上图,当配置文件中存在相同组的属性, 用户名 、 密码 、 年龄 都属于用户属性的抽象,按面向的规则我们可以抽取出一个 User 的 PO 类型使用 @ConfigurationProperties 将外部配置绑定到代码中的bean。同时可以像其他任何Spring bean一样在整个应用程序代码中注入和使用此bean。
user.username=lengleng user.password=123456 user.age=26
/**
* @author lengleng
* @date 2019-11-08
* <p>
* 2.2 之前版本,必须使用 @Component 或者 @Configuration 声明成Spring Bean
*/
@Component
@ConfigurationProperties(prefix = "user")
public class User {
private String username;
private String password;
private Integer age;
...
}
如上代码,当我们在使用 spring boot 2.2 之前版本 必须使用 @Component 或者 @Configuration 声明成Spring Bean,不然无法注入
ConfigurationProperties 和 @Value 的区别
2.2.0 新增一个 @ConfigurationPropertiesScan 的注解, 默认是开启的扫描 main 启动类所在的包路径的所有
ConfigurationProperties ,所以可以不用再加 @Component 或者 @Configuration
实际在使用过程中 你会发现 @Profile 和这个注解的兼容问题, @ConfigurationPropertiesScan not compatible with @Profile @ConfigurationProperties
所以 Spring Boot 2.2.1 默认关闭了这个功能
若想开启,只需要在 启动类加上
@Component
IDEA 2019.3 才会正式支持该注解