@ConfigurationProperties 实现流程

一、基本使用

  1. 创建配置对象
    对象上标注@ConfigurationProperties注解
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties implements 
BeanClassLoaderAware, InitializingBean {
private String driverClassName;
     /**
      * JDBC URL of the database.
      */
     private String url;
     /**
      * Login username of the database.
      */
     private String username;
     /**
      * Login password of the database.
      */
     private String password;

}

  1. 使用配置对象
  • 标注@EnableConfigurationProperties(配置对象类.class)
  • 一般用在@Configuration标注的类上
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(DataSourceProperties.class)
public class EmbeddedDataSourceConfiguration implements BeanClassLoaderAware {

	@Bean(destroyMethod = "shutdown")
	public EmbeddedDatabase dataSource(DataSourceProperties properties) {
		return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseConnection.get(this.classLoader).getType())
				.setName(properties.determineDatabaseName()).build();
	}

}

二、关键对象

  • ConfigurationPropertiesBindingPostProcessor:实现了BeanPostProcessor
    拦截@ConfigurationProperties标注bean的创建过程,注入值。
  • EnableConfigurationPropertiesRegistrar:将ConfigurationPropertiesBindingPostProcessor放入容器;将value属性值(标注@ConfigurationProperties的bean class)放入容器

三、实现流程

  1. ConfigurationPropertiesBindingPostProcessor类被加载和解析
标注了
调用
调用
@EnableConfigurationProperties
@Import(EnableConfigurationPropertiesRegistrar.class)
spring-boot解析@Import流程
EnableConfigurationPropertiesRegistrar.
registerBeanDefinitions()
registerInfrastructureBeans()
向容器添加了
ConfigurationPropertiesBindingPostProcessor
ConfigurationPropertiesBeanRegistrar.register()
将@EnableConfigurationProperties注解value属性值
(标注@ConfigurationProperties的bean class)放入容器
  1. 拦截@ConfigurationProperties标注bean的创建过程,注入值
调用
调用
调用
创建bean流程
ConfigurationPropertiesBindingPostProcessor.
postProcessBeforeInitialization()
ConfigurationPropertiesBean.get()
如果bean没有@ConfigurationProperties,则结束流程
bind()
ConfigurationPropertiesBinder.bind()
从applicationContext中获取配置文件值注入bean

你可能感兴趣的:(spring,java,spring)