Spring Boot源码分析 - Configuration注解

栏目: Java · 发布时间: 7年前

内容简介:使用实现了

@Configuration 注解指示一个类声明一个或多个@Bean方法, 并且可以由Spring容器处理, 以在运行时为这些bean生成bean定义和服务请求.

使用 ConfigurationClassParser 来对 @Configuration 标注的类进行解析, 封装成 ConfigurationClass 实例. 具体的实现通过 ConfigurationClassPostProcessor 来实现的.

ConfigurationClassPostProcessor

实现了 BeanDefinitionRegistryPostProcessor 接口, 间接实现了 BeanFactorPostProcessor 接口.

  • #postProcessBeanDefinitionRegistry() : 注册所有 ConfigurationClass 中的 BeanDefinition , 包括 @Bean 注解的方法, @ImporResource 引入的资源中定义的bean, 和 @Import 注解引入的 ImportBeanDefinitionRegistrar 中注册的 BeanDefinition
  • #postProcessBeanFactory() : 在运行时以通过 cglig 增强的类来替换 ConfigurationClass , 为服务bean请求做准备. 增强的实现是通过 ConfigurationClassEnhancer 完成的.

插入一点, ConfigurationClassEnhancer 实现了直接使用bean注册方法来获取bean的操作, 提供了一个 BeanMethodInterceptor 的内部类来实行.

@Configuration
public class Config {
    @Bean
    public A a() {
        ...
        return a;
    }
    @Bean
    public B b() {
        b.setA(a());
        ...
        return b;
    }
}

Full ConfigurationClass VS Lite ConfigurationClass

先说区别: full的 ConfigurationClass 会使用CGLIB进行增强.

查看类 ConfigurationClassUtils , 其中有两个方法 #isFullConfigurationClass()#isLiteConfigurationClass() .

方法的实现是去检查 BeanDefinition 中的 ConfigurationClassPostProcessor.configurationClass 属性, 是 full 还是 lite .

这个属性的值又来源于 #checkConfigurationClassCandidate() 方法, 如果 BeanDefinition 使用的是 @Configuration 注解, 则为 full ; 如果是 @Component , @ComponentScan , @Import 或者 @ImportResource 中的任何一种, 则为 lite . 如果是 ConfigurationClass , 则会继续为其添加顺序属性.

public static boolean checkConfigurationClassCandidate(BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) {
	...
	if (isFullConfigurationCandidate(metadata)) {
		beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
	}
	else if (isLiteConfigurationCandidate(metadata)) {
		beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
	}
	else {
		return false;
	}
	// It's a full or lite configuration candidate... Let's determine the order value, if any.
	Map<String, Object> orderAttributes = metadata.getAnnotationAttributes(Order.class.getName());
	if (orderAttributes != null) {
		beanDef.setAttribute(ORDER_ATTRIBUTE, orderAttributes.get(AnnotationUtils.VALUE));
	}
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Cracking the Coding Interview

Cracking the Coding Interview

Gayle Laakmann McDowell / CareerCup / 2015-7-1 / USD 39.95

Cracking the Coding Interview, 6th Edition is here to help you through this process, teaching you what you need to know and enabling you to perform at your very best. I've coached and interviewed hund......一起来看看 《Cracking the Coding Interview》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具