SpringBoot读取配置文件(@ConfigurationProperties、@EnableConfigurationProperties)


前言

  • 内容参考网上多篇优秀文章,结合自己理解写下该笔记

一、@ConfigurationProperties

1、介绍

  • @ConfigurationPropertiesSpringBoot提供读取配置文件的一个注解,其对应的的后置处理器为
    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();
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kimi-001

只想在有限的时间分享更多的知识

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值