概述
ConfigurationProperties是一个大家常用的注解。有一些系统配置,经常放在yml中,然后通过spring注入到bean中。
一般这些配置都是通过在spring生命周期的某一个环节,将属性注入进去的。
ConfigurationProperties就是利用了org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor接口在重写的postProcessBeforeInitialization方法中将yml中的配置set到bean中.(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记录了当前bean的prefix前缀。后面会根据这个前缀去读取对应配置,赋值到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)




















