先来看下大体的ConfigurationProperties注解处理函数的注册过程.这里说明一下该注解是在ConfigurationPropertiesBindingPostProcessor对象里,被postProcessBeforeInitialization函数进行处理的.流程图如下

spring boot configuration springbootconfigurationprop 注解_链表

这个过程有点复杂,对照着流程图一步一步来说.

1.一个springboot的应用由springbootAppliaction注解开始,该注解里面包括EnableAutoConfiguration注解

2.EnableAutoConfiguration注解,引入了AutoConfigurationImportSelector.class这个类,这个按照import注解处理将会被注册到bean Map中去.

3.spring启动的时候会进行自动化处理,而@import注解作为处理标志之一,第一步@import被处理.而第二步判断并处理ImportSelector类,这将触发processImports函数调用,来调用接口函数

4.AutoConfigurationImportSelector类的selectImports函数被调用

5.AutoConfigurationImportSelector这个函数调用,最终会去读取spring.factories文件,来获取EnableAutoConfiguration的属性,流程如下

selectImports->getAutoConfigurationEntry->getCandidateConfigurations

读取的结果会如下

spring boot configuration springbootconfigurationprop 注解_链表_02

这里面有个ConfigurationPropertiesAutoConfiguration类,这个类就是我们所需要的.

7.按照import注解的处理,这个类会继续被解析,因为它也是个import注解类

spring boot configuration springbootconfigurationprop 注解_链表_03

前面的操作只为引出EnableConfigurationProperties这个注解

8.

spring boot configuration springbootconfigurationprop 注解_子类_04

处理这里的import

9.由于EnableConfigurationPropertiesImportSelector这个类是@import引用进来的,所以继续走import注解流程.

10.EnableConfigurationPropertiesImportSelector这个类是ImportSelector接口类,走processImports操作

11.EnableConfigurationPropertiesImportSelector类的selectImports接口被调用,反正字符串数组.

12.当所有需要处理的注解处理完成之后,对结果处理统一处理.对所有selectImports返回的类名,其属于ImportBeanDefinitionRegistrar子类的,进行实例化操作.EnableConfigurationPropertiesImportSelector返回的是ConfigurationPropertiesBindingPostProcessorRegistrar这个类名,而这个类是ImportBeanDefinitionRegistrar子类

13.

14

15

16这几步就不细讲了,主要是为了生成一个注入ConfigurationPropertiesBindingPostProcessor.class的属性的对象.

17,将16生成的对象注册到Bean Map里面,需要注意的是这里生成的是GenericBeanDefinition对象如图

spring boot configuration springbootconfigurationprop 注解_子类_05

注入的class为ConfigurationPropertiesBindingPostProcessor,而这个类是BeanPostProcessor接口子类.这个要注意了,因为这个是后面关键处理一步的依据.因为这里只是被当作一个普通的bean注册到map中去,它最终应该去的地方是postProcess的List<>链表.那么它是在哪里被加载到post处理链表的呢.

答案是:spring refresh()函数处理完bean的注册后,的某一步操作如图

spring boot configuration springbootconfigurationprop 注解_链表_06

registerBeanPostProcessors这个函数就是我们需要的,现在来看它的实现

spring boot configuration springbootconfigurationprop 注解_子类_07

代码就不细说了,这里大体说下过程

1.从所有注册的bean里面找出BeanPostProcessor.class的子类.

2.实例化后调用addBeanPostProcessor函数把它们注册到

beanPostProcessors List链表中去.

好了,上面做了这么多事.主要目地就是实例化ConfigurationPropertiesBindingPostProcessor对象,然后注册到处理对象中去.注册过程到这里结束,那么回到这个标题上来,什么时候使用呢.

答案是getBean初始化的时候,大体流程图如下:

spring boot configuration springbootconfigurationprop 注解_链表_08

这里大家自行看代码吧.过程大体如此,如有错误敬请指出谢谢!