Spring Boot源码-@EnableConfigurationProperties @ConfigurationProperties注解配置原理


1 概述
2 实例
3 配置注入实现原理

1 概述

使用过Spring Boot的都会知道,我们可以在application.properties文件中进行一系列的配置,该配置会被自动注入到我们需要使用的bean中,下面我们就介绍配置注入的实现原理。

首先,要知道在application.properties中的配置是通过BeanPostProcessor进行注入的,具体完成该功能的BeanPostProcessor实现类是ConfigurationPropertiesBindingPostProcessor

本文接下来会介绍ConfigurationPropertiesBindingPostProcessor是在何时被加入到beanfactory中的,以及@EnableConfigurationProperties@ConfigurationProperties注解的实现原理。

2 实例

Spring Boot自动配置中充斥着大量使用通过application.properties进行扩展配置的实现,比如我们熟悉的MybatisAutoConfiguration

@Configuration
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnSingleCandidate(DataSource.class)
//使用MybatisProperties类获得application.properties中的实现
@EnableConfigurationProperties({MybatisProperties.class})
@AutoConfigureAfter({DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class})
public class MybatisAutoConfiguration implements InitializingBean {
    ...
}

下面我们在看下MybatisProperties类的定义:

//指定扩展配置在application.properties中的配置前缀为mybatis
@ConfigurationProperties(
    prefix = "mybatis"
)
public class MybatisProperties {
    public static final String MYBATIS_PREFIX = "mybatis";
    ...
}

通过如上的注解,MyBatis就可以获得我们在application.properties中的配置了,比如如下配置:

mybatis.config-location=classpath:configurations/mybatis/mybatis-config.xml

3 配置注入实现原理

要了解配置注入的实现原理,首先要找到上文介绍到的ConfigurationPropertiesBindingPostProcessor是何时被注册到beanfactory中的,通过阅读源码发现,在spring.factories文件中有如下一行:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
...
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
...

可见,是通过@EnableAutoConfiguration注解引入了相关的配置,@EnableAutoConfiguration通过@Import注解自动配置的原理这里不再介绍。我们看下ConfigurationPropertiesAutoConfiguration类的实现:

//两个重要的注解Configuration使得该类被视为配置类进行处理
//EnableConfigurationProperties则实现了配置注入
@Configuration
@EnableConfigurationProperties
public class ConfigurationPropertiesAutoConfiguration {

}

首先ConfigurationPropertiesAutoConfiguration@Configuration注解,因此会在beanfactory加载时被作为配置类处理,具体在ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry调用ConfigurationClassParser.parse进行处理。

我们再看@EnableConfigurationProperties定义:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(EnableConfigurationPropertiesImportSelector.class)
public @interface EnableConfigurationProperties {

    /**
     * Convenient way to quickly register {@link ConfigurationProperties} annotated beans
     * with Spring. Standard Spring Beans will also be scanned regardless of this value.
     * @return {@link ConfigurationProperties} annotated beans to register
     */
    Class[] value() default {};

}

@EnableConfigurationProperties通过@Import(EnableConfigurationPropertiesImportSelector.class)向容器中注入了相关的处理类,@Import也是在ConfigurationClassParser.parse进行处理的。

EnableConfigurationPropertiesImportSelector类定义如下:

class EnableConfigurationPropertiesImportSelector implements ImportSelector {

    private static final String[] IMPORTS = { ConfigurationPropertiesBeanRegistrar.class.getName(),
            ConfigurationPropertiesBindingPostProcessorRegistrar.class.getName() };

    //该类主要通过@Import实现机制向beanfactory进行了配置注入相关类的注册
    //其中ConfigurationPropertiesBeanRegistrar负责找到所有EnableConfigurationProperties
    //注解中声明的配置类,并将其注册到beanfactory中,如上面例子中的
    //@EnableConfigurationProperties({MybatisProperties.class}),
    //MybatisProperties将被注入到beanfactory中
    //ConfigurationPropertiesBindingPostProcessorRegistrar则负责
    //在实例化类时,检测该类是否被ConfigurationProperties注解,如果是的话
    //则从application.properties获取相应前缀的配置,然后进行配置注入
    @Override
    public String[] selectImports(AnnotationMetadata metadata) {
        return IMPORTS;
    }

    /**
     * {@link ImportBeanDefinitionRegistrar} for configuration properties support.
     */
    //ConfigurationPropertiesBeanRegistrar是EnableConfigurationPropertiesImportSelector的内部类
    public static class ConfigurationPropertiesBeanRegistrar implements ImportBeanDefinitionRegistrar {

        //向beanfactory中注入所有注解EnableConfigurationProperties.value中指定的配置类
        @Override
        public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
            getTypes(metadata).forEach((type) -> register(registry, (ConfigurableListableBeanFactory) registry, type));
        }

        //获取该配置类EnableConfigurationProperties.value中指定的配置类
        private List> getTypes(AnnotationMetadata metadata) {
            MultiValueMap attributes = metadata
                    .getAllAnnotationAttributes(EnableConfigurationProperties.class.getName(), false);
            return collectClasses((attributes != null) ? attributes.get("value") : Collections.emptyList());
        }

        private List> collectClasses(List values) {
            return values.stream().flatMap((value) -> Arrays.stream((Object[]) value)).map((o) -> (Class) o)
                    .filter((type) -> void.class != type).collect(Collectors.toList());
        }

        private void register(BeanDefinitionRegistry registry, ConfigurableListableBeanFactory beanFactory,
                Class type) {
            String name = getName(type);
            if (!containsBeanDefinition(beanFactory, name)) {
                registerBeanDefinition(registry, name, type);
            }
        }

        private String getName(Class type) {
            ConfigurationProperties annotation = AnnotationUtils.findAnnotation(type, ConfigurationProperties.class);
            String prefix = (annotation != null) ? annotation.prefix() : "";
            return (StringUtils.hasText(prefix) ? prefix + "-" + type.getName() : type.getName());
        }

        private boolean containsBeanDefinition(ConfigurableListableBeanFactory beanFactory, String name) {
            if (beanFactory.containsBeanDefinition(name)) {
                return true;
            }
            BeanFactory parent = beanFactory.getParentBeanFactory();
            if (parent instanceof ConfigurableListableBeanFactory) {
                return containsBeanDefinition((ConfigurableListableBeanFactory) parent, name);
            }
            return false;
        }

        private void registerBeanDefinition(BeanDefinitionRegistry registry, String name, Class type) {
            assertHasAnnotation(type);
            GenericBeanDefinition definition = new GenericBeanDefinition();
            definition.setBeanClass(type);
            registry.registerBeanDefinition(name, definition);
        }

        private void assertHasAnnotation(Class type) {
            Assert.notNull(AnnotationUtils.findAnnotation(type, ConfigurationProperties.class),
                    () -> "No " + ConfigurationProperties.class.getSimpleName() + " annotation found on  '"
                            + type.getName() + "'.");
        }

    }

}

好了,到这里,我们已经知道注解@EnableConfigurationProperties.value中指定的配置类是如何被注入到beanfactory中的了,那么注解EnableConfigurationProperties.value中指定的配置类中的属性是如何从application.properties被注入的呢?比如上面的

//指定扩展配置在application.properties中的配置前缀为mybatis
@ConfigurationProperties(
    prefix = "mybatis"
)
public class MybatisProperties {
    public static final String MYBATIS_PREFIX = "mybatis";
    ...
}

对应配置如下:

mybatis.config-location=classpath:configurations/mybatis/mybatis-config.xml

这就是我们前面提到的BeanPostProcessor接口实现类ConfigurationPropertiesBindingPostProcessor类处理的,而ConfigurationPropertiesBindingPostProcessor则是通过上面EnableConfigurationPropertiesImportSelector中使用类ConfigurationPropertiesBindingPostProcessorRegistrar进行注册的:

public class ConfigurationPropertiesBindingPostProcessorRegistrar implements ImportBeanDefinitionRegistrar {

    //通过如下方法注入了ConfigurationPropertiesBindingPostProcessor
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        if (!registry.containsBeanDefinition(ConfigurationPropertiesBindingPostProcessor.BEAN_NAME)) {
            registerConfigurationPropertiesBindingPostProcessor(registry);
            registerConfigurationBeanFactoryMetadata(registry);
        }
    }

    private void registerConfigurationPropertiesBindingPostProcessor(BeanDefinitionRegistry registry) {
        GenericBeanDefinition definition = new GenericBeanDefinition();
        definition.setBeanClass(ConfigurationPropertiesBindingPostProcessor.class);
        definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
        registry.registerBeanDefinition(ConfigurationPropertiesBindingPostProcessor.BEAN_NAME, definition);

    }

    private void registerConfigurationBeanFactoryMetadata(BeanDefinitionRegistry registry) {
        GenericBeanDefinition definition = new GenericBeanDefinition();
        definition.setBeanClass(ConfigurationBeanFactoryMetadata.class);
        definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
        registry.registerBeanDefinition(ConfigurationBeanFactoryMetadata.BEAN_NAME, definition);
    }

}

ConfigurationPropertiesBindingPostProcessor是接口BeanPostProcessor的实现,会被ApplicationContext检测出来,在实例化每个bean时会被调用进行扩展处理。

//ConfigurationPropertiesBindingPostProcessor
//类ConfigurationPropertiesBindingPostProcessor在方法postProcessBeforeInitialization
//进行配置注入,在下面的源码中可以看到我们熟悉的注解@ConfigurationProperties
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    ConfigurationProperties annotation = getAnnotation(bean, beanName, ConfigurationProperties.class);
    if (annotation != null) {
        bind(bean, beanName, annotation);
    }
    return bean;
}

你可能感兴趣的:(Spring Boot源码-@EnableConfigurationProperties @ConfigurationProperties注解配置原理)