文章目录
前言
- 内容参考网上多篇优秀文章,结合自己理解写下该笔记
一、@ConfigurationProperties
1、介绍
@ConfigurationProperties
是SpringBoot
提供读取配置文件的一个注解,其对应的的后置处理器为
ConfigurationPropertiesBindingPostProcessor
- 支持松散绑定,即配置文件:
驼峰userName
、中划线user-name
、下划线user_name
都可以用属性private String userName
接收,但推荐使用中划线格式,又叫烤肉串格式 - 该注解使用必须将对象注入到IOC容器中才有配置绑定的功能,该类必须有set、get方法
在类上、方法上添加
2、属性
//匹配的前缀 = prefix
@AliasFor("prefix")
String value() default "";
//匹配的前缀 = value
@AliasFor("value")
String prefix() default "";
//是否忽略 配置文件中配置值 和 类中属性 类型不匹配的字段,默认false
//true:如:在配置文件中声明了login.admin=admin,类中对应的属性应该用private String admin,但是如果使用private Integer admin,则项目启动会报错
boolean ignoreInvalidFields() default false;
//是否忽略 配置文件中声明了的配置值,在类中找不到对应的属性,默认true
//false:如:在配置文件中声明了login.admin=admin,但在类中找不到属性来对用它,则项目启动会报错;有助于我们及时删除一些无效的配置
boolean ignoreUnknownFields() default true;
3、添加位置
1)类上
-
这种方式适合项目中很多地方使用该配置,项目启动会将该类读取好配置文件内容放入IOC容器中
swagger: enable: true
//注入 @Component @ConfigurationProperties("swagger") public class SwaggerProperties{ private Boolean enable; } //使用 @Resource private SwaggerProperties swaggerProperties; swaggerProperties.getEnable();
2)方法上
- 这种方式适合只在某些配置类中使用,在加载该配置类时才会注入
swagger: enable: true
//读取swagger配置实体类 public class SwaggerProperties{ private Boolean enable; } //swagger配置类 @Configuration public class SwaggerAutoConfiguration{ //注入 @Bean @ConfigurationProperties("swagger") public SwaggerProperties swaggerProperties(){ return new SwaggerProperties(); } //使用 private ApiInfo apiInfo(SwaggerProperties swaggerProperties){ } }
二、@EnableConfigurationProperties
1、介绍
- 以上我们使用
@Component
将配置类放入Spring
的IOC容器中的,@Component
需要@ComponentScan
扫描才可以放入IOC容器中,有时候我们做的项目可能是一个工具包需要被其他项目使用或者上传到maven仓库供别人下载,若包不在扫描范围内,还需要用户自己手动配置额外的扫描包的范围,通常我们需要引入的依赖是非常多的,这就要写非常多的扫描包范围,这对于用户来说非常不友好,所以无法使用@ComponentScan
+@Component
这组合;@EnableConfigurationProperties
就是将Bean自动注入,这样用户引入依赖时无需关注依赖中的Bean扫描范围就会自动注册到IOC容器中
2、注入+使用
swagger:
enable: true
//自动注入
@EnableConfigurationProperties(SwaggerProperties.class)
@ConfigurationProperties("swagger")
public class SwaggerProperties{
private Boolean enable;
}
//使用
@Resource
private SwaggerProperties swaggerProperties;
swaggerProperties.getEnable();