注: 该源码分析对应 SpringBoot 版本为 2.1.0.RELEASE
1 温故而知新
本篇接 外部配置属性值是如何被绑定到 XxxProperties 类属性上的?--SpringBoot 源码 (五) https://juejin.im/post/5e689b49e51d4527143e5e2f
温故而知新, 我们来简单回顾一下上篇的内容, 上一篇我们分析了 SpringBoot 外部配置属性值是如何被绑定到 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 步.
- // A 的 pom.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <groupId>com.ymbj</groupId>
- <artifactId>A</artifactId>
- <version>1.0-SNAPSHOT</version>
- </project>
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <groupId>com.ymbj</groupId>
- <artifactId>B</artifactId>
- <version>1.0-SNAPSHOT</version>
- <!-- 注意是可选依赖 -->
- <dependencies>
- <dependency>
- <groupId>com.ymbj</groupId>
- <artifactId>A</artifactId>
- <version>1.0-SNAPSHOT</version>
- <optional>true</optional>
- </dependency>
- </dependencies>
- </project>
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <groupId>com.ymbj</groupId>
- <artifactId>C</artifactId>
- <version>1.0-SNAPSHOT</version>
- <dependencies>
- <dependency>
- <groupId>com.ymbj</groupId>
- <artifactId>B</artifactId>
- <version>1.0-SNAPSHOT</version>
- </dependency>
- </dependencies>
- </project>
来源: https://www.cnblogs.com/ymbj/p/12498895.html