SpringBoot之@ConfigurationProperties自动注入成员变量值功能源码解析

本文深入探讨了SpringBoot中@ConfigurationProperties注解的工作原理,通过一系列步骤揭示了SpringBoot如何自动注入配置文件中的属性值到Bean的成员变量。从@SpringBootApplication的@EnableAutoConfiguration开始,逐步分析了AutoConfigurationImportSelector、ConfigurationPropertiesAutoConfiguration和ConfigurationPropertiesBindingPostProcessor等关键组件,最终解释了ConfigurationPropertiesBindingPostProcessor如何完成属性注入。
摘要由CSDN通过智能技术生成

个人博客导航页(点击右侧链接即可打开个人博客):大牛带你入门技术栈 

前言:

    我们在使用SpringBoot开发相关项目时,经常会使用到@ConfigurationProperties注解,这个注解配合application.properties(或yml文件)使用,可以快速的为我们的Bean的成员变量进行赋值,常规用法如下:

// 创建bean
@ConfigurationProperties(prefix="person")
@Data
public class Person {
    private int id;
    private String name;
    private String addr;
}
 
// 在application.properties文件中添加
person.name=jack
person.id=11
person.addr=china
    这样就可以为Person实例自动注入属性

    那么SpringBoot是如何为bean实例注入属性值的呢?

 

 

1.关于自动注入属性值的功能猜想

    SpringBoot会为每一个在配置文件中有匹配项的bean注入属性值,根据之前的 BeanPostProcessor功能可知,我们的Spring容器中应该有一个Bean实现BeanPostProcessor接口,然后在返回每一个bean之前,获取配置文件内容,找到对应属性,然后进行赋值操作

    SpringBoot中确实有这么一个Bean,ConfigurationPropertiesBindingPostProcessor,实现了相关赋值功能,那么这个Bean是如何被注入到容器中的呢,下面亲随笔者一层层分析查找

 

 

2.SpringBoot项目启动之@SpringBootApplication

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
        @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
    重要的注解就是@EnableAutoConfiguration,下面看下这个注解

@SuppressWarnings("deprecation")
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
    主要功能就是把EnableAutoConfigurationImportSelector注入到容器中,下面看下这个类

public class EnableAutoConfigurationImportSelector
        extends AutoConfigurationImportSelector {
 
    @Override
    protected boolean isEnabled(AnnotationMetadata metadata) {
        if (getClass().equals(EnableAutoConfigurationImportSelector.class)) {
            return getEnvironment().getProperty(
                    EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY, Boolean.class,
                    true);
        }
        return true;
    }
 
}
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值