Python实战社群
Java实战社群
长按识别下方二维码,按需求添加
扫码关注添加客服
进Python社群▲
扫码关注添加客服
进Java社群▲
作者丨爱编码的码农
来源丨源码笔记(jinyue_lll)
注:该源码分析对应SpringBoot版本为2.1.0.RELEASE
1 前言
本篇接 SpringBoot是如何实现自动配置的?--SpringBoot源码(四)
温故而知新,我们来简单回顾一下上篇的内容,上一篇我们分析了SpringBoot的自动配置的相关源码,自动配置相关源码主要有以下几个重要的步骤:
从spring.factories配置文件中加载自动配置类;
加载的自动配置类中排除掉
@EnableAutoConfiguration
注解的exclude
属性指定的自动配置类;然后再用
AutoConfigurationImportFilter
接口去过滤自动配置类是否符合其标注注解(若有标注的话)@ConditionalOnClass
,@ConditionalOnBean
和@ConditionalOnWebApplication
的条件,若都符合的话则返回匹配结果;然后触发
AutoConfigurationImportEvent
事件,告诉ConditionEvaluationReport
条件评估报告器对象来分别记录符合条件和exclude
的自动配置类。最后spring再将最后筛选后的自动配置类导入IOC容器中
本篇继续来分析SpringBoot的自动配置的相关源码,我们来分析下@EnableConfigurationProperties
和@EnableConfigurationProperties
这两个注解,来探究下外部配置属性值是如何被绑定到@ConfigurationProperties注解的类属性中的?
举个栗子:以配置web项目的服务器端口为例,若我们要将服务器端口配置为
8081
,那么我们会在application.properties
配置文件中配置server.port=8081
,此时该配置值8081
就将会绑定到被@ConfigurationProperties
注解的类ServerProperties
的属性port
上,从而使得配置生效。
2 @EnableConfigurationProperties
我们接着前面的设置服务器端口的栗子来分析,我们先直接来看看ServerProperties
的源码,应该能找到源码的入口:
1@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
2public class ServerProperties {
3 /**
4 * Server HTTP port.
5 */
6 private Integer port;
7 // ...省略非关键代码
8}
可以看到,ServerProperties
类上标注了@ConfigurationProperties
这个注解,服务器属性配置前缀为server
,是否忽略未知的配置值(ignoreUnknownFields
)设置为true
。
那么我们再来看下@ConfigurationProperties
这个注解的源码:
1@Target({ ElementType.TYPE, ElementType.METHOD })
2@Retention(RetentionPolicy.RUNTIME)
3@Documented
4public @interface ConfigurationProperties {
5
6 // 前缀别名
7 @AliasFor("prefix")
8 String value() default "";
9
10 // 前缀
11 @AliasFor("value")
12 String prefix() default "";
13
14 // 忽略无效的配置属性
15 boolean ignoreInvalidFields() default false;
16
17 // 忽略未知的配置属性
18 boolean ignoreUnknownFields() default true;
19}
@ConfigurationProperties
这个注解的作用就是将外部配置的配置值绑定到其注解的类的属性上,可以作用于配置类或配置类的方法上。可以看到@ConfigurationProperties
注解除了有设置前缀,是否忽略一些不存在或无效的配置等属性等外,这个注解没有其他任何的处理逻辑,可以看到@ConfigurationProperties
是一个标志性的注解,源码入口不在这里。
这里讲的是服务器的自动配置,自然而然的,我们来看下自动配置类ServletWebServerFactoryAutoConfiguration
的源码:
1@Configuration
2@EnableConfigurationProperties(ServerProperties.class)
3// ...省略非关键注解
4public class ServletWebServerFactoryAutoConfiguration {
5 // ...省略非关键代码
6}
为了突出重点,我已经把ServletWebServerFactoryAutoConfiguration
的非关键代码和非关键注解省略掉了。可以看到,ServletWebServerFactoryAutoConfiguration
自动配置类中有一个@EnableConfigurationProperties
注解,且注解值是前面讲的ServerProperties.class
,因此@EnableConfigurationProperties
注解肯定就是我们关注的重点了。
同样,再来看下@EnableConfigurationProperties
注解的源码:
1@Target(ElementType.TYPE)
2@Retention(RetentionPolicy.RUNTIME)
3@Documented
4@Import(EnableConfigurationPropertiesImportSelector.class)
5public @interface EnableConfigurationProperties {
6
7 // 这个值指定的类就是@ConfigurationProperties注解标注的类,其将会被注册到spring容器中
8 Class<?>[] value() default {};
9
10}
@EnableConfigurationProperties
注解的主要作用就是为@ConfigurationProperties
注解标注的类提供支持,即对将外部配置属性值(比如application.properties配置值)绑定到@ConfigurationProperties
标注的类的属性中。
注意:SpringBoot源码中还存在了
ConfigurationPropertiesAutoConfiguration
这个自动配置类,同时spring.factories
配置文件中的EnableAutoConfiguration
接口也配置了ConfigurationPropertiesAutoConfiguration
,这个自动配置类上也有@EnableConfigurationProperties
这个注解,对属性绑定进行了默认开启。
那么,@EnableConfigurationProperties
这个注解对属性绑定提供怎样的支持呢?
可以看到@EnableConfigurationProperties
这个注解上还标注了@Import(EnableConfigurationPropertiesImportSelector.class)
,其导入了EnableConfigurationPropertiesImportSelector
,因此可以肯定的是@EnableConfigurationProperties
这个注解对属性绑定提供的支持必定跟EnableConfigurationPropertiesImportSelector
有关。
到了这里,EnableConfigurationPropertiesImportSelector
这个哥们是我们接下来要分析的对象,那么我们下面继续来分析EnableConfigurationPropertiesImportSelector
是如何承担将外部配置属性值绑定到@ConfigurationProperties
标注的类的属性中的。
3 EnableConfigurationPropertiesImportSelector
EnableConfigurationPropertiesImportSelector
类的作用主要用来处理外部属性绑定的相关逻辑,其实现了ImportSelector
接口,我们都知道,实现ImportSelector
接口的selectImports
方法可以向容器中注册bean。
那么,我们来看下EnableConfigurationPropertiesImportSelector
覆写的selectImports
方法:
1// EnableConfigurationPropertiesImportSelector.java
2
3class EnableConfigurationPropertiesImportSelector implements ImportSelector {
4 // IMPORTS数组即是要向spring容器中注册的bean
5 private static final String[] IMPORTS = {
6 ConfigurationPropertiesBeanRegistrar.class.getName(),
7 ConfigurationPropertiesBindingPostProcessorRegistrar.class.getName() };
8
9 @Override
10 public String[] selectImports(AnnotationMetadata metadata) {
11 // 返回ConfigurationPropertiesBeanRegistrar和ConfigurationPropertiesBindingPostProcessorRegistrar的全限定名
12 // 即上面两个类将会被注册到Spring容器中
13 return IMPORTS;
14 }
15
16}
可以看到EnableConfigurationPropertiesImportSelector
类中的selectImports
方法中返回的是IMPORTS
数组,而这个IMPORTS
是一个常量数组,值是ConfigurationPropertiesBeanRegistrar
和ConfigurationPropertiesBindingPostProcessorRegistrar
。即EnableConfigurationPropertiesImportSelector
的作用是向Spring容器中注册了ConfigurationPropertiesBeanRegistrar
和ConfigurationPropertiesBindingPostProcessorRegistrar
这两个bean
。
我们在EnableConfigurationPropertiesImportSelector
类中没看到处理外部属性绑定的相关逻辑,其只是注册了ConfigurationPropertiesBeanRegistrar
和ConfigurationPropertiesBindingPostProcessorRegistrar
这两个bean
,接下来我们再看下注册的这两个bean
类。
4 ConfigurationPropertiesBeanRegistrar
我们先来看下ConfigurationPropertiesBeanRegistrar
这个类。
ConfigurationPropertiesBeanRegistrar
是EnableConfigurationPropertiesImportSelector
的内部类,其实现了ImportBeanDefinitionRegistrar
接口,覆写了registerBeanDefinitions
方法。可见,ConfigurationPropertiesBeanRegistrar
又是用来注册一些bean
definition
的,即也是向Spring
容器中注册一些bean。
先看下ConfigurationPropertiesBeanRegistrar
的源码:
1// ConfigurationPropertiesBeanRegistrar$ConfigurationPropertiesBeanRegistrar.java
2
3public static class ConfigurationPropertiesBeanRegistrar
4 implements ImportBeanDefinitionRegistrar {
5 @Override
6 public void registerBeanDefinitions(AnnotationMetadata metadata, // metadata是AnnotationMetadataReadingVisitor对象,存储了某个配置类的元数据
7 BeanDefinitionRegistry registry) {
8 // (1)得到@EnableConfigurationProperties注解的所有属性值,
9 // 比如@EnableConfigurationProperties(ServerProperties.class),那么得到的值是ServerProperties.class
10 // (2)然后再将得到的@EnableConfigurationProperties注解的所有属性值注册到容器中
11 getTypes(metadata).forEach((type) -> register(registry,
12 (ConfigurableListableBeanFactory) registry, type));
13 }
14}
在ConfigurationPropertiesBeanRegistrar
实现的registerBeanDefinitions
中,可以看到主要做了两件事:
调用
getTypes
方法获取@EnableConfigurationProperties
注解的属性值XxxProperties
;调用
register
方法将获取的属性值XxxProperties
注册到Spring
容器中,用于以后和外部属性绑定时使用。
我们来看下getTypes
方法的源码:
1// ConfigurationPropertiesBeanRegistrar$ConfigurationPropertiesBeanRegistrar.java
2
3private List<Class<?>> getTypes(AnnotationMetadata metadata) {
4 // 得到@EnableConfigurationProperties注解的所有属性值,
5 // 比如@EnableConfigurationProperties(ServerProperties.class),那么得到的值是ServerProperties.class
6 MultiValueMap<String, Object> attributes = metadata
7 .getAllAnnotationAttributes(
8 EnableConfigurationProperties.class.getName(), false);
9 // 将属性值取出装进List集合并返回
10 return collectClasses((attributes != null) ? attributes.get("value")
11 : Collections.emptyList());
12}
getTypes
方法里面的逻辑很简单即将@EnableConfigurationProperties
注解里面的属性值XxxProperties
(比如ServerProperties.class
)取出并装进List
集合并返回。
由getTypes
方法拿到@EnableConfigurationProperties
注解里面的属性值XxxProperties
(比如ServerProperties.class
)后,此时再遍历将XxxProperties
逐个注册进Spring
容器中,我们来看下register
方法:
1// ConfigurationPropertiesBeanRegistrar$ConfigurationPropertiesBeanRegistrar.java
2
3private void register(BeanDefinitionRegistry registry,
4 ConfigurableListableBeanFactory beanFactory, Class<?> type) {
5 // 得到type的名字,一般用类的全限定名作为bean name
6 String name = getName(type);
7 // 根据bean name判断beanFactory容器中是否包含该bean
8 if (!containsBeanDefinition(beanFactory, name)) {
9 // 若不包含,那么注册bean definition
10 registerBeanDefinition(registry, name, type);
11 }
12}
我们再来看下由EnableConfigurationPropertiesImportSelector
导入的另一个类ConfigurationPropertiesBindingPostProcessorRegistrar
又是干嘛的呢?
5 ConfigurationPropertiesBindingPostProcessorRegistrar
可以看到ConfigurationPropertiesBindingPostProcessorRegistrar
类名字又是以Registrar
单词为结尾,说明其肯定又是导入一些bean
definition
的。直接看源码:
1// ConfigurationPropertiesBindingPostProcessorRegistrar.java
2
3public class ConfigurationPropertiesBindingPostProcessorRegistrar
4 implements ImportBeanDefinitionRegistrar {
5
6 @Override
7 public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
8 BeanDefinitionRegistry registry) {
9 // 若容器中没有注册ConfigurationPropertiesBindingPostProcessor这个处理属性绑定的后置处理器,
10 // 那么将注册ConfigurationPropertiesBindingPostProcessor和ConfigurationBeanFactoryMetadata这两个bean
11 // 注意onApplicationEnvironmentPreparedEvent事件加载配置属性在先,然后再注册一些后置处理器用来处理这些配置属性
12 if (!registry.containsBeanDefinition(
13 ConfigurationPropertiesBindingPostProcessor.BEAN_NAME)) {
14 // (1)注册ConfigurationPropertiesBindingPostProcessor后置处理器,用来对配置属性进行后置处理
15 registerConfigurationPropertiesBindingPostProcessor(registry);
16 // (2)注册一个ConfigurationBeanFactoryMetadata类型的bean,
17 // 注意ConfigurationBeanFactoryMetadata实现了BeanFactoryPostProcessor,然后其会在postProcessBeanFactory中注册一些元数据
18 registerConfigurationBeanFactoryMetadata(registry);
19 }
20 }
21 // 注册ConfigurationPropertiesBindingPostProcessor后置处理器
22 private void registerConfigurationPropertiesBindingPostProcessor(
23 BeanDefinitionRegistry registry) {
24 GenericBeanDefinition definition = new GenericBeanDefinition();
25 definition.setBeanClass(ConfigurationPropertiesBindingPostProcessor.class);
26 definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
27 registry.registerBeanDefinition(
28 ConfigurationPropertiesBindingPostProcessor.BEAN_NAME, definition);
29
30 }
31 // 注册ConfigurationBeanFactoryMetadata后置处理器
32 private void registerConfigurationBeanFactoryMetadata(
33 BeanDefinitionRegistry registry) {
34 GenericBeanDefinition definition = new GenericBeanDefinition();
35 definition.setBeanClass(ConfigurationBeanFactoryMetadata.class);
36 definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
37 registry.registerBeanDefinition(ConfigurationBeanFactoryMetadata.BEAN_NAME,
38 definition);
39 }
40
41}
ConfigurationPropertiesBindingPostProcessorRegistrar
类的逻辑非常简单,主要用来注册外部配置属性绑定相关的后置处理器即ConfigurationBeanFactoryMetadata
和ConfigurationPropertiesBindingPostProcessor
。
那么接下来我们再来探究下注册的这两个后置处理器又是执行怎样的后置处理逻辑呢?
6 ConfigurationBeanFactoryMetadata
先来看ConfigurationBeanFactoryMetadata
这个后置处理器,其实现了BeanFactoryPostProcessor
接口的postProcessBeanFactory
方法,在初始化bean
factory
时将@Bean
注解的元数据存储起来,以便在后续的外部配置属性绑定的相关逻辑中使用。
先来看下ConfigurationBeanFactoryMetadata
类实现BeanFactoryPostProcessor
接口的postProcessBeanFactory
方法源码:
1// ConfigurationBeanFactoryMetadata
2
3public class ConfigurationBeanFactoryMetadata implements BeanFactoryPostProcessor {
4
5 /**
6 * The bean name that this class is registered with.
7 */
8 public static final String BEAN_NAME = ConfigurationBeanFactoryMetadata.class
9 .getName();
10
11 private ConfigurableListableBeanFactory beanFactory;
12 /**
13 * beansFactoryMetadata集合存储beansFactory的元数据
14 * key:某个bean的名字 value:FactoryMetadata对象(封装了工厂bean名和工厂方法名)
15 * 比如下面这个配置类:
16 *
17 * @Configuration
18 * public class ConfigA {
19 * @Bean
20 * public BeanXXX methodB(configA, ) {
21 * return new BeanXXX();
22 * }
23 * }
24 *
25 * 那么:key值为"methodB",value为FactoryMetadata(configA, methodB)对象,其bean属性值为"configA",method属性值为"methodB"
26 */
27 private final Map<String, FactoryMetadata> beansFactoryMetadata = new HashMap<>();
28
29 @Override
30 public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
31 throws BeansException {
32 this.beanFactory = beanFactory;
33 // 遍历beanFactory的beanDefinitionName,即每个bean的名字(比如工厂方法对应的bean名字)
34 for (String name : beanFactory.getBeanDefinitionNames()) {
35 // 根据name得到beanDefinition
36 BeanDefinition definition = beanFactory.getBeanDefinition(name);
37 // 工厂方法名:一般是注解@Bean的方法名
38 String method = definition.getFactoryMethodName();
39 // 工厂bean名:一般是注解@Configuration的类名
40 String bean = definition.getFactoryBeanName();
41 if (method != null && bean != null) {
42 // 将beanDefinitionName作为Key,封装了工厂bean名和工厂方法名的FactoryMetadata对象作为value装入beansFactoryMetadata中
43 this.beansFactoryMetadata.put(name, new FactoryMetadata(bean, method));
44 }
45 }
46 }
47}
从上面代码可以看到ConfigurationBeanFactoryMetadata
类覆写的postProcessBeanFactory
方法做的事情就是将工厂Bean
(可以理解为@Configuration
注解的类)及其@Bean
注解的工厂方法的一些元数据缓存到beansFactoryMetadata
集合中,以便后续使用,这个后面会详述。
由上代码中我们看到了ConfigurationBeanFactoryMetadata
类的beansFactoryMetadata
集合类型是Map<String, FactoryMetadata>
,那么我们再来看下封装相关工厂元数据的FactoryMetadata
类:
1// ConfigurationBeanFactoryMetadata$FactoryMetadata.java
2
3private static class FactoryMetadata {
4 // @Configuration注解的配置类的类名
5 private final String bean;
6 // @Bean注解的方法名
7 private final String method;
8
9 FactoryMetadata(String bean, String method) {
10 this.bean = bean;
11 this.method = method;
12 }
13
14 public String getBean() {
15 return this.bean;
16 }
17
18 public String getMethod() {
19 return this.method;
20 }
21
22}
FactoryMetadata
仅有两个属性bean
和method
,分别表示@Configuration
注解的工厂bean
和@Bean
注解的工厂方法。
上面说了那么多,直接举个栗子会更直观:
1/**
2 * beansFactoryMetadata集合存储beansFactory的元数据
3 * key:某个bean的名字 value:FactoryMetadata对象(封装了工厂bean名和工厂方法名)
4 * 比如下面这个配置类:
5 *
6 * @Configuration
7 * public class ConfigA {
8 * @Bean
9 * public BeanXXX methodB(configA, ) {
10 * return new BeanXXX();
11 * }
12 * }
13 *
14 * 那么:key值为"methodB",value为FactoryMetadata(configA, methodB)对象,其bean属性值为"configA",method属性值为"methodB"
15 */
16 private final Map<String, FactoryMetadata> beansFactoryMetadata = new HashMap<>();
为了更好理解上面beansFactoryMetadata
集合存储的数据是啥,建议最好自己动手调试看看其里面装的是什么哦。总之这里记住一点就好了:ConfigurationBeanFactoryMetadata
类的beansFactoryMetadata
集合存储的是工厂bean
的相关元数据,以便在ConfigurationPropertiesBindingPostProcessor
后置处理器中使用。
7 ConfigurationPropertiesBindingPostProcessor
我们再来看下ConfigurationPropertiesBindingPostProcessorRegistrar
类注册的另外一个后置处理器ConfigurationPropertiesBindingPostProcessor
,这个后置处理器就尤其重要了,主要承担了将外部配置属性绑定到@ConfigurationProperties
注解标注的XxxProperties类的属性中(比如application.properties
配置文件中设置了server.port=8081
,那么8081
将会绑定到ServerProperties
类的port
属性中)的实现逻辑。
同样,先来看下ConfigurationPropertiesBindingPostProcessor
的源码:
1// ConfigurationPropertiesBindingPostProcessor.java
2
3public class ConfigurationPropertiesBindingPostProcessor implements BeanPostProcessor,
4 PriorityOrdered, ApplicationContextAware, InitializingBean {
5 @Override
6 public void afterPropertiesSet() throws Exception {
7 // ...这里省略实现代码先
8 }
9
10 @Override
11 public Object postProcessBeforeInitialization(Object bean, String beanName) {
12 // ...这里省略实现代码先
13 }
14
15 // ...省略非关键代码
16}
可以看到ConfigurationPropertiesBindingPostProcessor
后置处理器实现了两个重要的接口InitializingBean
和BeanPostProcessor
。
我们都知道:
InitializingBean
接口的afterPropertiesSet
方法会在bean
属性赋值后调用,用来执行一些自定义的初始化逻辑比如检查某些强制的属性是否有被赋值,校验某些配置或给一些未被赋值的属性赋值。
BeanPostProcessor
接口是bean
的后置处理器,其有postProcessBeforeInitialization
和postProcessAfterInitialization
两个勾子方法,分别会在bean
初始化前后被调用来执行一些后置处理逻辑,比如检查标记接口或是否用代理包装了bean
。
同时由上代码可以看到ConfigurationPropertiesBindingPostProcessor
后置处理器覆写了InitializingBean
的afterPropertiesSet
方法和BeanPostProcessor
的postProcessBeforeInitialization
方法。
接下来我们再来探究ConfigurationPropertiesBindingPostProcessor
后置处理器覆写的两个方法的源码。
7.1 在执行外部属性绑定逻辑前先准备好相关元数据和配置属性绑定器
我们先来分析下ConfigurationPropertiesBindingPostProcessor
覆写InitializingBean
接口的afterPropertiesSet
方法:
1// ConfigurationPropertiesBindingPostProcessor.java
2
3 /**
4 * 配置属性校验器名字
5 */
6 public static final String VALIDATOR_BEAN_NAME = "configurationPropertiesValidator";
7 /**
8 * 工厂bean相关元数据
9 */
10 private ConfigurationBeanFactoryMetadata beanFactoryMetadata;
11 /**
12 * 上下文
13 */
14 private ApplicationContext applicationContext;
15 /**
16 * 配置属性绑定器
17 */
18 private ConfigurationPropertiesBinder configurationPropertiesBinder;
19
20
21 // 这里主要是给beanFactoryMetadata和configurationPropertiesBinder的属性赋值,用于后面的后置处理器方法处理属性绑定的时候用
22 @Override
23 public void afterPropertiesSet() throws Exception {
24 // We can't use constructor injection of the application context because
25 // it causes eager factory bean initialization
26 // 【1】利用afterPropertiesSet这个勾子方法从容器中获取之前注册的ConfigurationBeanFactoryMetadata对象赋给beanFactoryMetadata属性
27 // (问1)beanFactoryMetadata这个bean是什么时候注册到容器中的?
28 // (答1)在ConfigurationPropertiesBindingPostProcessorRegistrar类的registerBeanDefinitions方法中将beanFactoryMetadata这个bean注册到容器中
29 // (问2)从容器中获取beanFactoryMetadata对象后,什么时候会被用到?
30 // (答2)beanFactoryMetadata对象的beansFactoryMetadata集合保存的工厂bean相关的元数据,在ConfigurationPropertiesBindingPostProcessor类
31 // 要判断某个bean是否有FactoryAnnotation或FactoryMethod时会根据这个beanFactoryMetadata对象的beansFactoryMetadata集合的元数据来查找
32 this.beanFactoryMetadata = this.applicationContext.getBean(
33 ConfigurationBeanFactoryMetadata.BEAN_NAME,
34 ConfigurationBeanFactoryMetadata.class);
35 // 【2】new一个ConfigurationPropertiesBinder,用于后面的外部属性绑定时使用
36 this.configurationPropertiesBinder = new ConfigurationPropertiesBinder(
37 this.applicationContext, VALIDATOR_BEAN_NAME); // VALIDATOR_BEAN_NAME="configurationPropertiesValidator"
38 }
可以看到以上代码主要逻辑就是在执行外部属性绑定逻辑前先准备好相关元数据和配置属性绑定器,即从Spring
容器中获取到之前注册的ConfigurationBeanFactoryMetadata
对象赋给ConfigurationPropertiesBindingPostProcessor
后置处理器的beanFactoryMetadata
属性,还有就是新建一个ConfigurationPropertiesBinder
配置属性绑定器对象并赋值给configurationPropertiesBinder
属性。
我们再来看下ConfigurationPropertiesBinder
这个配置属性绑定器对象是如何构造的。
1// ConfigurationPropertiesBinder.java
2
3ConfigurationPropertiesBinder(ApplicationContext applicationContext,
4 String validatorBeanName) {
5 this.applicationContext = applicationContext;
6 // 将applicationContext封装到PropertySourcesDeducer对象中并返回
7 this.propertySources = new PropertySourcesDeducer(applicationContext)
8 .getPropertySources(); // 获取属性源,主要用于在ConfigurableListableBeanFactory的后置处理方法postProcessBeanFactory中处理
9 // 如果没有配置validator的话,这里一般返回的是null
10 this.configurationPropertiesValidator = getConfigurationPropertiesValidator(
11 applicationContext, validatorBeanName);
12 // 检查实现JSR-303规范的bean校验器相关类在classpath中是否存在
13 this.jsr303Present = ConfigurationPropertiesJsr303Validator
14 .isJsr303Present(applicationContext);
15}
可以看到在构造ConfigurationPropertiesBinder
对象时主要给其相关属性赋值(一般构造器逻辑都是这样):
给
applicationContext
属性赋值注入上下文对象;给
propertySources
属性赋值,属性源即外部配置值比如application.properties
配置的属性值,注意这里的属性源是由ConfigFileApplicationListener
这个监听器负责读取的,ConfigFileApplicationListener
将会在后面源码分析章节中详述。给
configurationPropertiesValidator
属性赋值,值来自Spring
容器中名为configurationPropertiesValidator
的bean
。给
jsr303Present
属性赋值,当javax.validation.Validator
,javax.validation.ValidatorFactory
和javax.validation.bootstrap.GenericBootstrap"
这三个类同时存在于classpath
中jsr303Present
属性值才为true
。
关于JSR303:
JSR-303
是JAVA EE 6中的一项子规范,叫做Bean Validation
,Hibernate Validator
是Bean Validation
的参考实现 。Hibernate Validator
提供了JSR 303
规范中所有内置constraint
的实现,除此之外还有一些附加的constraint
。
7.2 执行真正的外部属性绑定逻辑【主线】
前面分析了那么多,发现都还没到外部属性绑定的真正处理逻辑,前面步骤都是在做一些准备性工作,为外部属性绑定做铺垫。
在执行外部属性绑定逻辑前,准备好了相关元数据和配置属性绑定器后,此时我们再来看看ConfigurationPropertiesBindingPostProcessor
实现BeanPostProcessor
接口的postProcessBeforeInitialization
后置处理方法了,外部属性绑定逻辑都是在这个后置处理方法里实现,是我们关注的重中之重。
直接看代码:
1// ConfigurationPropertiesBindingPostProcessor.java
2
3// 因为是外部配置属性后置处理器,因此这里对@ConfigurationProperties注解标注的XxxProperties类进行后置处理完成属性绑定
4@Override
5public Object postProcessBeforeInitialization(Object bean, String beanName)
6 throws BeansException {
7 // 注意,BeanPostProcessor后置处理器默认会对所有的bean进行处理,因此需要根据bean的一些条件进行过滤得到最终要处理的目的bean,
8 // 这里的过滤条件就是判断某个bean是否有@ConfigurationProperties注解
9 // 【1】从bean上获取@ConfigurationProperties注解,若bean有标注,那么返回该注解;若没有,则返回Null。比如ServerProperty上标注了@ConfigurationProperties注解
10 ConfigurationProperties annotation = getAnnotation(bean, beanName,
11 ConfigurationProperties.class);
12 // 【2】若标注有@ConfigurationProperties注解的bean,那么则进行进一步处理:将配置文件的配置注入到bean的属性值中
13 if (annotation != null) {
14 /********主线,重点关注】********/
15 bind(bean, beanName, annotation);
16 }
17 // 【3】返回外部配置属性值绑定后的bean(一般是XxxProperties对象)
18 return bean;
19}
ConfigurationPropertiesBindingPostProcessor
类覆写的postProcessBeforeInitialization
方法的做的事情就是将外部属性配置绑定到@ConfigurationProperties
注解标注的XxxProperties
类上,现关键步骤总结如下:
从
bean
上获取@ConfigurationProperties
注解;若标注有
@ConfigurationProperties
注解的bean
,那么则进行进一步的处理:将外部配置属性值绑定到bean的属性值中后再返回bean
;若没有标注有@ConfigurationProperties
注解的bean
,那么将直接原样返回bean
。
注意:后置处理器默认会对每个容器中的
bean
进行后置处理,因为这里只针对标注有@ConfigurationProperties
注解的bean
进行外部属性绑定,因此没有标注@ConfigurationProperties
注解的bean
将不会被处理。
接下来我们紧跟主线,再来看下外部配置属性是如何绑定到@ConfigurationProperties
注解的XxxProperties
类属性上的呢?
直接看代码:
1// ConfigurationPropertiesBindingPostProcessor.java
2
3private void bind(Object bean, String beanName, ConfigurationProperties annotation) {
4 // 【1】得到bean的类型,比如ServerPropertie这个bean得到的类型是:org.springframework.boot.autoconfigure.web.ServerProperties
5 ResolvableType type = getBeanType(bean, beanName);
6 // 【2】获取bean上标注的@Validated注解
7 Validated validated = getAnnotation(bean, beanName, Validated.class);
8 // 若标注有@Validated注解的话则跟@ConfigurationProperties注解一起组成一个Annotation数组
9 Annotation[] annotations = (validated != null)
10 ? new Annotation[] { annotation, validated }
11 : new Annotation[] { annotation };
12 // 【3】返回一个绑定了XxxProperties类的Bindable对象target,这个target对象即被外部属性值注入的目标对象
13 // (比如封装了标注有@ConfigurationProperties注解的ServerProperties对象的Bindable对象)
14 Bindable<?> target = Bindable.of(type).withExistingValue(bean)
15 .withAnnotations(annotations); // 设置annotations属性数组
16 try {
17 // 【4】执行外部配置属性绑定逻辑
18 /********【主线,重点关注】********/
19 this.configurationPropertiesBinder.bind(target);
20 }
21 catch (Exception ex) {
22 throw new ConfigurationPropertiesBindException(beanName, bean, annotation,
23 ex);
24 }
25}
关键步骤上面代码已经标注【x】
,这里在继续讲解外部配置属性绑定的主线逻辑(在8 ConfigurationPropertiesBinder这一小节分析 )前先穿插一个知识点,还记得ConfigurationBeanFactoryMetadata
覆写的postProcessBeanFactory
方法里已经将相关工厂bean
的元数据封装到ConfigurationBeanFactoryMetadata
类的beansFactoryMetadata
集合这一回事吗?
我们再来看下上面代码中的【1】getBeanType
和【2】getAnnotation
方法源码:
1// ConfigurationPropertiesBindingPostProcessor.java
2
3private ResolvableType getBeanType(Object bean, String beanName) {
4 // 首先获取有没有工厂方法
5 Method factoryMethod = this.beanFactoryMetadata.findFactoryMethod(beanName);
6 // 若有工厂方法
7 if (factoryMethod != null) {
8 return ResolvableType.forMethodReturnType(factoryMethod);
9 }
10 // 没有工厂方法,则说明是普通的配置类
11 return ResolvableType.forClass(bean.getClass());
12}
13
14private <A extends Annotation> A getAnnotation(Object bean, String beanName,
15 Class<A> type) {
16 A annotation = this.beanFactoryMetadata.findFactoryAnnotation(beanName, type);
17 if (annotation == null) {
18 annotation = AnnotationUtils.findAnnotation(bean.getClass(), type);
19 }
20 return annotation;
21}
注意到上面代码中的beanFactoryMetadata
对象没,ConfigurationPropertiesBindingPostProcessor
后置处理器的getBeanType
和getAnnotation
方法分别会调用ConfigurationBeanFactoryMetadata
的findFactoryMethod
和findFactoryAnnotation
方法,而ConfigurationBeanFactoryMetadata
的findFactoryMethod
和findFactoryAnnotation
方法又会依赖存储工厂bean
元数据的beansFactoryMetadata
集合来寻找是否有FactoryMethod
和FactoryAnnotation
。因此,到这里我们就知道之ConfigurationBeanFactoryMetadata
的beansFactoryMetadata
集合存储工厂bean
元数据的作用了。
8 ConfigurationPropertiesBinder
我们再继续紧跟外部配置属性绑定的主线,继续前面看7.2 执行真正的外部属性绑定逻辑中的this.configurationPropertiesBinder.bind(target);
这句代码:
1// ConfigurationPropertiesBinder.java
2
3public void bind(Bindable<?> target) {
4 //【1】得到@ConfigurationProperties注解
5 ConfigurationProperties annotation = target
6 .getAnnotation(ConfigurationProperties.class);
7 Assert.state(annotation != null,
8 () -> "Missing @ConfigurationProperties on " + target);
9 // 【2】得到Validator对象集合,用于属性校验
10 List<Validator> validators = getValidators(target);
11 // 【3】得到BindHandler对象(默认是IgnoreTopLevelConverterNotFoundBindHandler对象),
12 // 用于对ConfigurationProperties注解的ignoreUnknownFields等属性的处理
13 BindHandler bindHandler = getBindHandler(annotation, validators);
14 // 【4】得到一个Binder对象,并利用其bind方法执行外部属性绑定逻辑
15 /********************【主线,重点关注】********************/
16 getBinder().bind(annotation.prefix(), target, bindHandler);
17}
上面代码的主要逻辑是:
先获取
target
对象(对应XxxProperties
类)上的@ConfigurationProperties
注解和校验器(若有);然后再根据获取的的
@ConfigurationProperties
注解和校验器来获得BindHandler
对象,BindHandler
的作用是用于在属性绑定时来处理一些附件逻辑;在8.1节分析.最后再获取一个
Binder
对象,调用其bind
方法来执行外部属性绑定的逻辑,在8.2节分析.
8.1 获取BindHandler对象以便在属性绑定时来处理一些附件逻辑
我们在看getBindHandler
方法的逻辑前先来认识下BindHandler
是干啥的。
BindHandler
是一个父类接口,用于在属性绑定时来处理一些附件逻辑。我们先看下BindHandler
的类图,好有一个整体的认识:
图1
可以看到AbstractBindHandler
作为抽象基类实现了BindHandler
接口,其又有四个具体的子类分别是IgnoreTopLevelConverterNotFoundBindHandler
,NoUnboundElementsBindHandler
,IgnoreErrorsBindHandler
和ValidationBindHandler
。
IgnoreTopLevelConverterNotFoundBindHandler
:在处理外部属性绑定时的默认BindHandler
,当属性绑定失败时会忽略最顶层的ConverterNotFoundException
;NoUnboundElementsBindHandler
:用来处理配置文件配置的未知的属性;IgnoreErrorsBindHandler
:用来忽略无效的配置属性例如类型错误;ValidationBindHandler
:利用校验器对绑定的结果值进行校验。
分析完类关系后,我们再来看下BindHandler
接口提供了哪些方法在外部属性绑定时提供一些额外的附件逻辑,直接看代码:
1// BindHandler.java
2
3public interface BindHandler {
4
5 /**
6 * Default no-op bind handler.
7 */
8 BindHandler DEFAULT = new BindHandler() {
9
10 };
11
12 // onStart方法在外部属性绑定前被调用
13 default <T> Bindable<T> onStart(ConfigurationPropertyName name, Bindable<T> target,
14 BindContext context) {
15 return target;
16 }
17
18 // onSuccess方法在外部属性成功绑定时被调用,该方法能够改变最终返回的属性值或对属性值进行校验
19 default Object onSuccess(ConfigurationPropertyName name, Bindable<?> target,
20 BindContext context, Object result) {
21 return result;
22 }
23
24 // onFailure方法在外部属性绑定失败(包括onSuccess方法里的逻辑执行失败)时被调用,
25 // 该方法可以用来catch住相关异常或者返回一个替代的结果(跟微服务的降级结果有点类似,嘿嘿)
26 default Object onFailure(ConfigurationPropertyName name, Bindable<?> target,
27 BindContext context, Exception error) throws Exception {
28 throw error;
29 }
30
31 // 当外部属性绑定结束时(不管绑定成功还是失败)被调用
32 default void onFinish(ConfigurationPropertyName name, Bindable<?> target,
33 BindContext context, Object result) throws Exception {
34 }
35}
可以看到BindHandler
接口定义了onStart
,onSuccess
,onFailure
和onFinish
方法,这四个方法分别会在执行外部属性绑定时的不同时机会被调用,在属性绑定时用来添加一些额外的处理逻辑,比如在onSuccess
方法改变最终绑定的属性值或对属性值进行校验,在onFailure
方法catch
住相关异常或者返回一个替代的绑定的属性值。
知道了BindHandler
是在属性绑定时添加一些额外的附件处理逻辑后,我们再来看下getBindHandler
方法的逻辑,直接上代码:
1// ConfigurationPropertiesBinder.java
2
3// 注意BindHandler的设计技巧,应该是责任链模式,非常巧妙,值得借鉴
4private BindHandler getBindHandler(ConfigurationProperties annotation,
5 List<Validator> validators) {
6 // 新建一个IgnoreTopLevelConverterNotFoundBindHandler对象,这是个默认的BindHandler对象
7 BindHandler handler = new IgnoreTopLevelConverterNotFoundBindHandler();
8 // 若注解@ConfigurationProperties的ignoreInvalidFields属性设置为true,
9 // 则说明可以忽略无效的配置属性例如类型错误,此时新建一个IgnoreErrorsBindHandler对象
10 if (annotation.ignoreInvalidFields()) {
11 handler = new IgnoreErrorsBindHandler(handler);
12 }
13 // 若注解@ConfigurationProperties的ignoreUnknownFields属性设置为true,
14 // 则说明配置文件配置了一些未知的属性配置,此时新建一个ignoreUnknownFields对象
15 if (!annotation.ignoreUnknownFields()) {
16 UnboundElementsSourceFilter filter = new UnboundElementsSourceFilter();
17 handler = new NoUnboundElementsBindHandler(handler, filter);
18 }
19 // 如果@Valid注解不为空,则创建一个ValidationBindHandler对象
20 if (!validators.isEmpty()) {
21 handler = new ValidationBindHandler(handler,
22 validators.toArray(new Validator[0]));
23 }
24 // 遍历获取的ConfigurationPropertiesBindHandlerAdvisor集合,
25 // ConfigurationPropertiesBindHandlerAdvisor目前只在测试类中有用到
26 for (ConfigurationPropertiesBindHandlerAdvisor advisor : getBindHandlerAdvisors()) {
27 // 对handler进一步处理
28 handler = advisor.apply(handler);
29 }
30 // 返回handler
31 return handler;
32}
getBindHandler
方法的逻辑很简单,主要是根据传入的@ConfigurationProperties
注解和validators
校验器来创建不同的BindHandler
具体实现类:
首先
new
一个IgnoreTopLevelConverterNotFoundBindHandler
作为默认的BindHandler
;若
@ConfigurationProperties
注解的属性ignoreInvalidFields
值为true
,那么再new
一个IgnoreErrorsBindHandler
对象,把刚才新建的IgnoreTopLevelConverterNotFoundBindHandler
对象作为构造参数传入赋值给AbstractBindHandler
父类的parent
属性;若
@ConfigurationProperties
注解的属性ignoreUnknownFields
值为false
,那么再new
一个UnboundElementsSourceFilter
对象,把之前构造的BindHandler
对象作为构造参数传入赋值给AbstractBindHandler
父类的parent
属性;……以此类推,前一个
handler
对象作为后一个hangdler
对象的构造参数,就这样利用AbstractBindHandler
父类的parent
属性将每一个handler
链起来,最后再得到最终构造的handler
。
GET技巧:上面的这个设计模式是不是很熟悉,这个就是责任链模式。我们学习源码,同时也是学习别人怎么熟练运用设计模式。责任链模式的应用案例有很多,比如
Dubbo
的各种Filter
们(比如AccessLogFilter
是用来记录服务的访问日志的,ExceptionFilter
是用来处理异常的…),我们一开始学习java web时的Servlet
的Filter
,MyBatis
的Plugin
们以及Netty
的Pipeline
都采用了责任链模式。
我们了解了BindHandler
的作用后,再来紧跟主线,看属性绑定是如何绑定的?
8.2 获取Binder对象用于进行属性绑定【主线】
这里接8 ConfigurationPropertiesBinder节代码中标注【4】
的主线代码getBinder().bind(annotation.prefix(), target, bindHandler);
.
可以看到这句代码主要做了两件事:
调用
getBinder
方法获取用于属性绑定的Binder
对象;调用
Binder
对象的bind
方法进行外部属性绑定到@ConfigurationProperties
注解的XxxProperties
类的属性上。
那么我们先看下getBinder
方法源码:
1// ConfigurationPropertiesBinder.java
2
3private Binder getBinder() {
4 // Binder是一个能绑定ConfigurationPropertySource的容器对象
5 if (this.binder == null) {
6 // 新建一个Binder对象,这个binder对象封装了ConfigurationPropertySources,
7 // PropertySourcesPlaceholdersResolver,ConversionService和PropertyEditorInitializer对象
8 this.binder = new Binder(getConfigurationPropertySources(), // 将PropertySources对象封装成SpringConfigurationPropertySources对象并返回
9 getPropertySourcesPlaceholdersResolver(), getConversionService(), // 将PropertySources对象封装成PropertySourcesPlaceholdersResolver对象并返回,从容器中获取到ConversionService对象
10 getPropertyEditorInitializer()); // 得到Consumer<PropertyEditorRegistry>对象,这些初始化器用来配置property editors,property editors通常可以用来转换值
11 }
12 // 返回binder
13 return this.binder;
14}
可以看到Binder
对象封装了ConfigurationPropertySources
,PropertySourcesPlaceholdersResolver
,ConversionService
和PropertyEditorInitializer
这四个对象,Binder
对象封装了这四个哥们肯定是在后面属性绑定逻辑中会用到,先看下这四个对象是干嘛的:
ConfigurationPropertySources
:外部配置文件的属性源,由ConfigFileApplicationListener
监听器负责触发读取;PropertySourcesPlaceholdersResolver
:解析属性源中的占位符${}
;ConversionService
:对属性类型进行转换PropertyEditorInitializer
:用来配置property editors
那么,我们获取了Binder
属性绑定器后,再来看下它的bind
方法是如何执行属性绑定的。
1// Binder.java
2
3public <T> BindResult<T> bind(String name, Bindable<T> target, BindHandler handler) {
4 // ConfigurationPropertyName.of(name):将name(这里指属性前缀名)封装到ConfigurationPropertyName对象中
5 // 将外部配置属性绑定到目标对象target中
6 return bind(ConfigurationPropertyName.of(name), target, handler);
7}
8
9public <T> BindResult<T> bind(ConfigurationPropertyName name, Bindable<T> target,
10 BindHandler handler) {
11 Assert.notNull(name, "Name must not be null");
12 Assert.notNull(target, "Target must not be null");
13 handler = (handler != null) ? handler : BindHandler.DEFAULT;
14 // Context是Binder的内部类,实现了BindContext,Context可以理解为Binder的上下文,可以用来获取binder的属性比如Binder的sources属性
15 Context context = new Context();
16 // 进行属性绑定,并返回绑定属性后的对象bound,注意bound的对象类型是T,T就是@ConfigurationProperties注解的类比如ServerProperties
17 /********【主线,重点关注】************/
18 T bound = bind(name, target, handler, context, false);
19 // 将刚才返回的bound对象封装到BindResult对象中并返回
20 return BindResult.of(bound);
21}
上面代码中首先创建了一个Context
对象,Context
是Binder
的内部类,为Binder
的上下文,利用Context
上下文可以获取Binder
的属性比如获取Binder
的sources
属性值并绑定到XxxProperties
属性中。然后我们再紧跟主线看下bind(name, target, handler, context, false)
方法源码:
1// Binder.java
2
3protected final <T> T bind(ConfigurationPropertyName name, Bindable<T> target,
4 BindHandler handler, Context context, boolean allowRecursiveBinding) {
5 // 清空Binder的configurationProperty属性值
6 context.clearConfigurationProperty();
7 try {
8 // 【1】调用BindHandler的onStart方法,执行一系列的责任链对象的该方法
9 target = handler.onStart(name, target, context);
10 if (target == null) {
11 return null;
12 }// 【2】调用bindObject方法对Bindable对象target的属性进行绑定外部配置的值,并返回赋值给bound对象。
13 // 举个栗子:比如设置了server.port=8888,那么该方法最终会调用Binder.bindProperty方法,最终返回的bound的value值为8888
14 /************【主线:重点关注】***********/
15 Object bound = bindObject(name, target, handler, context,
16 allowRecursiveBinding);
17 // 【3】封装handleBindResult对象并返回,注意在handleBindResult的构造函数中会调用BindHandler的onSucess,onFinish方法
18 return handleBindResult(name, target, handler, context, bound);
19 }
20 catch (Exception ex) {
21 return handleBindError(name, target, handler, context, ex);
22 }
23}
上面代码的注释已经非常详细,这里不再详述。我们接着紧跟主线来看看bindObject
方法源码:
1// Binder.java
2
3private <T> Object bindObject(ConfigurationPropertyName name, Bindable<T> target,
4 BindHandler handler, Context context, boolean allowRecursiveBinding) {
5 // 从propertySource中的配置属性,获取ConfigurationProperty对象property即application.properties配置文件中若有相关的配置的话,
6 // 那么property将不会为null。举个栗子:假如你在配置文件中配置了spring.profiles.active=dev,那么相应property值为dev;否则为null
7 ConfigurationProperty property = findProperty(name, context);
8 // 若property为null,则不会执行后续的属性绑定相关逻辑
9 if (property == null && containsNoDescendantOf(context.getSources(), name)) {
10 // 如果property == null,则返回null
11 return null;
12 }
13 // 根据target类型获取不同的Binder,可以是null(普通的类型一般是Null),MapBinder,CollectionBinder或ArrayBinder
14 AggregateBinder<?> aggregateBinder = getAggregateBinder(target, context);
15 // 若aggregateBinder不为null比如配置了spring.profiles属性(当然包括其子属性比如spring.profiles.active等)
16 if (aggregateBinder != null) {
17 // 若aggregateBinder不为null,则调用bindAggregate并返回绑定后的对象
18 return bindAggregate(name, target, handler, context, aggregateBinder);
19 }
20 // 若property不为null
21 if (property != null) {
22 try {
23 // 绑定属性到对象中,比如配置文件中设置了server.port=8888,那么将会最终调用bindProperty方法进行属性设置
24 return bindProperty(target, context, property);
25 }
26 catch (ConverterNotFoundException ex) {
27 // We might still be able to bind it as a bean
28 Object bean = bindBean(name, target, handler, context,
29 allowRecursiveBinding);
30 if (bean != null) {
31 return bean;
32 }
33 throw ex;
34 }
35 }
36 // 只有@ConfigurationProperties注解的类进行外部属性绑定才会走这里
37 /***********************【主线,重点关注】****************************/
38 return bindBean(name, target, handler, context, allowRecursiveBinding);
39}
由上代码中可以看到bindObject
中执行属性绑定的逻辑会根据不同的属性类型进入不同的绑定逻辑中,举个栗子:
application.properties
配置文件中配置了spring.profiles.active=dev
的话,那么将会进入return bindAggregate(name, target, handler, context, aggregateBinder);
这个属性绑定的代码逻辑;application.properties
配置文件中配置了server.port=8081
的话,那么将会进入return bindBean(name, target, handler, context, allowRecursiveBinding);
的属性绑定的逻辑。
因此我们再次紧跟主线,进入@ConfigurationProperties
注解的XxxProperties
类的属性绑定逻辑中的bindBean
方法中:
1// Binder.java
2
3private Object bindBean(ConfigurationPropertyName name, Bindable<?> target, // name指的是ConfigurationProperties的前缀名
4 BindHandler handler, Context context, boolean allowRecursiveBinding) {
5 // 这里做一些ConfigurationPropertyState的相关检查
6 if (containsNoDescendantOf(context.getSources(), name)
7 || isUnbindableBean(name, target, context)) {
8 return null;
9 }// 这里新建一个BeanPropertyBinder的实现类对象,注意这个对象实现了bindProperty方法
10 BeanPropertyBinder propertyBinder = (propertyName, propertyTarget) -> bind(
11 name.append(propertyName), propertyTarget, handler, context, false);
12 /**
13 * (propertyName, propertyTarget) -> bind(
14 * name.append(propertyName), propertyTarget, handler, context, false);
15 * 等价于
16 * new BeanPropertyBinder() {
17 * Object bindProperty(String propertyName, Bindable<?> target){
18 * bind(name.append(propertyName), propertyTarget, handler, context, false);
19 * }
20 * }
21 */
22 // type类型即@ConfigurationProperties注解标注的XxxProperties类
23 Class<?> type = target.getType().resolve(Object.class);
24 if (!allowRecursiveBinding && context.hasBoundBean(type)) {
25 return null;
26 }
27 // 这里应用了java8的lambda语法,作为没怎么学习java8的lambda语法的我,不怎么好理解下面的逻辑,哈哈
28 // 真正实现将外部配置属性绑定到@ConfigurationProperties注解的XxxProperties类的属性中的逻辑应该就是在这句lambda代码了
29 /*******************【主线】***************************/
30 return context.withBean(type, () -> {
31 Stream<?> boundBeans = BEAN_BINDERS.stream()
32 .map((b) -> b.bind(name, target, context, propertyBinder));
33 return boundBeans.filter(Objects::nonNull).findFirst().orElse(null);
34 });
35 // 根据上面的lambda语句翻译如下:
36 /** 这里的T指的是各种属性绑定对象,比如ServerProperties
37 * return context.withBean(type, new Supplier<T>() {
38 * T get() {
39 * Stream<?> boundBeans = BEAN_BINDERS.stream()
40 * .map((b) -> b.bind(name, target, context, propertyBinder));
41 * return boundBeans.filter(Objects::nonNull).findFirst().orElse(null);
42 * }
43 * });
44 */
45}
从上面代码中,我们追根究底来到了外部配置属性绑定到XxxProperties
类属性中的比较底层的代码了,可以看到属性绑定的逻辑应该就在上面代码标注【主线】
的lambda
代码处了。这里就不再详述了,因为这个属于SpringBoot的属性绑定Binder
的范畴,Binder
相关类是SpringBoot2.0才出现的,即对之前的属性绑定相关代码进行推翻重写了。属性绑定相关的源码也比较多,后续有需要再另开一篇来分析探究吧。
9 小结
好了,外部配置属性值是如何被绑定到XxxProperties
类属性上的源码分析就到此结束了,又是蛮长的一篇文章,不知自己表述清楚没,重要步骤现总结下:
首先是
@EnableConfigurationProperties
注解import
了EnableConfigurationPropertiesImportSelector
后置处理器;EnableConfigurationPropertiesImportSelector
后置处理器又向Spring
容器中注册了ConfigurationPropertiesBeanRegistrar
和ConfigurationPropertiesBindingPostProcessorRegistrar
这两个bean
;其中
ConfigurationPropertiesBeanRegistrar
向Spring
容器中注册了XxxProperties
类型的bean
;ConfigurationPropertiesBindingPostProcessorRegistrar
向Spring
容器中注册了ConfigurationBeanFactoryMetadata
和ConfigurationPropertiesBindingPostProcessor
两个后置处理器;ConfigurationBeanFactoryMetadata
后置处理器在初始化bean
factory
时将@Bean
注解的元数据存储起来,以便在后续的外部配置属性绑定的相关逻辑中使用;ConfigurationPropertiesBindingPostProcessor
后置处理器将外部配置属性值绑定到XxxProperties
类属性的逻辑委托给ConfigurationPropertiesBinder
对象,然后ConfigurationPropertiesBinder
对象又最终将属性绑定的逻辑委托给Binder
对象来完成。
可见,重要的是上面的第5步。
由于笔者水平有限,若文中有错误还请指出,谢谢。
PS:本来打算这篇开始分析SpringBoot的启动流程的,但是回过头去看看自动配置的相关源码,还有蛮多没有分析的,因此再来一波自动配置相关的源码先。
参考:
1,https://www.jianshu.com/p/554533f88370
程序员专栏 扫码关注填加客服 长按识别下方二维码进群
近期精彩内容推荐: 再见,纸币!中国成全球首个数字货币国家! 张一鸣:为什么BAT挖不走我们的人才? 记一次 Python Web 接口优化 Java new一个对象时发生了什么?
在看点这里好文分享给更多人↓↓