ConfigurationProperties将配置绑定到bean的过程分析

概述

ConfigurationProperties是一个大家常用的注解。有一些系统配置,经常放在yml中,然后通过spring注入到bean中。

一般这些配置都是通过在spring生命周期的某一个环节,将属性注入进去的。

ConfigurationProperties就是利用了org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor接口在重写的postProcessBeforeInitialization方法中将yml中的配置setbean中.(ConfigurationPropertiesBindingPostProcessor继承了BeanPostProcessor 接口,在Bean对象实例化和依赖注入完毕后,在调用初始化方法前可以添加对应的修改。)

源码流程分析

当前我的springboot版本是
spring-boot-2.7.4.jar

进入注解源码,果然一开头就看到一个后置处理器。顺藤摸瓜继续点进去,可以看到实现了org.springframework.beans.factory.config.BeanPostProcessor接口
org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor重写的
postProcessBeforeInitialization方法中看到了一个关键的bind方法。

bind方法的入参是一个org.springframework.boot.context.properties.ConfigurationPropertiesBean对象。这个ConfigurationPropertiesBean记录了当前beanprefix前缀。后面会根据这个前缀去读取对应配置,赋值到bean属性中。

在这里插入图片描述

在这里插入图片描述

ConfigurationPropertiesBean.get获取一个ConfigurationPropertiesBean实例,实例内包含了当前bean,以及bean上的ConfigurationProperties注解信息等
在这里插入图片描述

org.springframework.boot.context.properties.ConfigurationPropertiesBinder#bind

在这里插入图片描述

绑定属性值到bean里
org.springframework.boot.context.properties.bind.Binder#bindDataObject
在这里插入图片描述

循环遍历属性,一个个绑定上去
org.springframework.boot.context.properties.bind.JavaBeanBinder#bind(org.springframework.boot.context.properties.bind.DataObjectPropertyBinder, org.springframework.boot.context.properties.bind.JavaBeanBinder.Bean, org.springframework.boot.context.properties.bind.JavaBeanBinder.BeanSupplier, org.springframework.boot.context.properties.bind.Binder.Context)

在这里插入图片描述

获取属性的值set到对象中去
org.springframework.boot.context.properties.bind.JavaBeanBinder#bind(org.springframework.boot.context.properties.bind.JavaBeanBinder.BeanSupplier, org.springframework.boot.context.properties.bind.DataObjectPropertyBinder, org.springframework.boot.context.properties.bind.JavaBeanBinder.BeanProperty)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值