IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> 五、Spring源码-容器启动Bean的注册 -> 正文阅读

[Java知识库]五、Spring源码-容器启动Bean的注册

spring_start

代码清单5-1 为例介绍其中一种基于注解的容器AnnotationConfigApplicationContext的启动流程

/**
 * @author Rab
 * @since 2022-04-24
 */
public class App {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);

        Person person = applicationContext.getBean(Person.class);

        System.out.println(person);
    }
}

1.构造方法

/**
  * 创建一个新的AnnotationConfigApplicationContext,从给定的annotated classes,
  * 并自动刷新上下文。
  *
  * @param annotatedClasses – one or more annotated classes, e.g. @Configuration classes
**/
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
		this();
		register(annotatedClasses);
		refresh();
}

this()

public AnnotationConfigApplicationContext() {
		this.reader = new AnnotatedBeanDefinitionReader(this);
		this.scanner = new ClassPathBeanDefinitionScanner(this);
}

1.1 BeanDefinitionReader

??通常情况下,需要根据不同的外部配置文件格式,给出相应的BeanDefinitionReader实现类,由 BeanDefinitionReader 的相应实现类负责将相应的配置文件内容读取并映射到 BeanDefinition ,然后将映射后的 BeanDefinition 注册到一个 BeanDefinitionRegistry ,之后, BeanDefinitionRegistry 即完成Bean的注册和加载.

??BeanDefinitionRegistry 即完成Bean的注册和加载。当然,大部分工作,包括解析文件格式、装配 BeanDefinition 之类的工作,都是由 BeanDefinitionReader 的相应实现类来做的,

AnnotatedBeanDefinitionReader

/**
 * 为给定的registry创建一个新的AnnotatedBeanDefinitionReader。如果registry是EnvironmentCapable,例如ApplicationContext,则Environment将被继承,否
 * 则将创建并使用一个新的StandardEnvironment。
 *
**/
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
  this(registry, getOrCreateEnvironment(registry));
}

1.2 BeanDefinitionRegistry

??BeanFactory 只是一个接口,我们最终需要一个该接口的实现来进行实际的Bean的管理, DefaultListableBeanFactory就是这么一个比较通用的 BeanFactory 实现类。 DefaultListableBeanFactory 除了间接地实现了 BeanFactory 接口,还实现了 BeanDefinitionRegistry 接口,该接口才是在 BeanFactory 的实现中担当Bean注册管理的角色。基本上, BeanFactory 接口只定义如何访问容器内管理的Bean的方法,各个 BeanFactory 的具体实现类负责具体Bean的注册以及管理工作。BeanDefinitionRegistry 接口定义抽象了Bean的注册逻辑。通常情况下,具体的 BeanFactory 实现类会实现这个接口来管理Bean的注册

spring_registry

??每一个受管的对象,在容器中都会有一个 BeanDefinition的实例(instance)与之相对应,该BeanDefinition 的实例负责保存对象的所有必要信息,包括其对应的对象的class类型、是否是抽象类、构造方法参数以及其他属性等。当客户端向 BeanFactory 请求相应对象的时候, BeanFactory 会通过这些信息为客户端返回一个完备可用的对象实例。 RootBeanDefinition 和 ChildBeanDefinition 是 BeanDefinition 的两个主要实现类。

1.3 EnvironmentCapable

??首先,带有Capable后缀的接口在Spring中带有getXXX的含义,也就是实现了这个接口,就可以通过该接口的实例获取到XXX,这个和Aware接口很类似。

??所以,这里的EnvironmentCapable接口就是可以获得一个Environment实例。看下接口定义:

public interface EnvironmentCapable {

/**
	* Return the {@link Environment} associated with this component.
	*/
Environment getEnvironment();            

}

??Environment也是一个接口,继承了PropertyResolver接口,是对获取属性的抽象。有两个常见的实现类:StandardEnvironment和StandardServletEnvironment,分别应用于非web和web应用中。

??Spring高级容器ApplicationContext接口继承了EnvironmentCapable接口,所以具备了获取Environment的能力。其中的getEnvironment方法的实现是在AbstractApplicationContext中:

@Override
public ConfigurableEnvironment getEnvironment() {
	if (this.environment == null) {
		this.environment = createEnvironment();
	}
	return this.environment;
}
protected ConfigurableEnvironment createEnvironment() {
	return new StandardEnvironment();
}

??可以看到,第一次调用,会创建一个StandardEnvironment的实例。在该类中,会默认加载两种属性源:

protected void customizePropertySources(MutablePropertySources propertySources) {
	propertySources.addLast(new MapPropertySource(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties()));
	propertySources.addLast(new SystemEnvironmentPropertySource(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment()));
}

??分别是系统属性和jvm属性。

1.4 AnnotatedBeanDefinitionReader构造方法

/**
 * 使用给定的registry和environment创建一个新的AnnotatedBeanDefinitionReader
 *
**/
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
  Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
  Assert.notNull(environment, "Environment must not be null");
  this.registry = registry;
  this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
  AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
  • ConditionEvaluator:用于解析@Conditional注解的内部类。

1.5 AnnotationConfigUtils

/**
* 在给定的registry注册所有相关的annotation post processors
* @param registry the registry to operate on
*/
public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
		registerAnnotationConfigProcessors(registry, null);
}
/**
* 在给定的registry注册所有相关的annotation post processors
*
* @param registry the registry to operate on
* @param source the configuration source element (already extracted)
* that this registration was triggered from. May be {@code null}.
* @return BeanDefinitionHolders集合, 包含所有bean definitions
*/
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
			BeanDefinitionRegistry registry, @Nullable Object source) {
		// 1.获取对应的BeanFactory
		DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
		if (beanFactory != null) {
			// 2.BeanFactory注入AnnotationAwareOrderComparator
			// AnnotationAwareOrderComparator是OrderComparator的扩展,
			// 它支持Spring的org.springframework.core.Ordered接口以及@Order和@Priority注释
			if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
				beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
			}
			// 3.BeanFactory注入ContextAnnotationAutowireCandidateResolver
			// AutowireCandidateResolver的完整实现,提供了@Lazy注解的解析
			// 继承自QualifierAnnotationAutowireCandidateResolver,提供了对@Qualifier注解的解析
			if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
				beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
			}
		}

		Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(4);

		// 注入<...internalConfigurationAnnotationProcessor, ConfigurationClassPostProcessor.class>
		// 内部管理带有@Configuration的BeanFactoryPostProcessor
		if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
		}
		// 注入<...internalAutowiredAnnotationProcessor, AutowiredAnnotationBeanPostProcessor.class>
		// 内部管理带有@Autowired注解的BeanPostProcessor
		if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
		}
		// 注入<...internalRequiredAnnotationProcessor, RequiredAnnotationBeanPostProcessor.class>
		// 内部管理带有@Required注解的BeanPostProcessor
		if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// 检查是否需要注入JSR250相应注解的解析器,即@Resource
		// 注入<...internalCommonAnnotationProcessor, CommonAnnotationBeanPostProcessor.class>
		// 内部管理带有JSR250注解的BeanPostProcessor
		if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// 检查是否需要支持JPA相关注解<...internalPersistenceAnnotationProcessor, PersistenceAnnotationBeanPostProcessor>
		// 内部管理带有JPA相关注解的BeanPostProcessor
		if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition();
			try {
				def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
						AnnotationConfigUtils.class.getClassLoader()));
			}
			catch (ClassNotFoundException ex) {
				throw new IllegalStateException(
						"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
			}
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
		}
		// 注入<...internalEventListenerProcessor, EventListenerMethodProcessor.class>
		// 内部管理@EventListener
		if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
		}
		// 注入<...internalEventListenerFactory, DefaultEventListenerFactory.class>
		// @EventListener的工厂
		if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
		}

		return beanDefs;
	}

1.6 插手“容器的启动”-BeanFactoryPostProcessor

??Spring提供了一种叫做BeanFactoryPostProcessor的容器扩展机制。该机制允许我们在容器实例化相应对象之前,对注册到容器的 BeanDefinition 所保存的信息做相应的修改。这就相当于在容器实现的第一阶段最后加入一道工序,让我们对最终的 BeanDefinition 做一些额外的操作,比如修改其中bean定义的某些属性,为bean定义增加其他信息等。

??如果要自定义实现 BeanFactoryPostProcessor ,通常我们需要实现 org.springframework.beans.factory.config.BeanFactoryPostProcessor 接口。同时,因为一个容器可能拥有多个 Bean-FactoryPostProcessor ,这个时候可能需要实现类同时实现Spring的 org.springframework.core.Ordered 接口,以保证各个 BeanFactoryPostProcessor 可以按照预先设定的顺序执行(如果顺序紧要的话)。

1.7 总结

AnnotationConfigApplicationContext构造方法

  • 调用父类构造方法,即:GenericApplicationContext,创建工厂

    public GenericApplicationContext() {
    	this.beanFactory = new DefaultListableBeanFactory();
    }
    
  • 创建AnnotatedBeanDefinitionReader,主要工作:加载相应的BeanDefinition进容器

  • 创建ClassPathBeanDefinitionScanner,主要工作:扫描classPath下面的bean,带有@Component注解相关

    protected void registerDefaultFilters() {
    	this.includeFilters.add(new AnnotationTypeFilter(Component.class));
    	.....
    }
    

AnnotatedBeanDefinitionReader构造方法

  • 创建Environment,即:StandardEnvironment,供ConditionEvaluator使用
  • 给对应的IoC容器注入相关的BeanDefinition

2.注入我们自己的Bean:register(annotatedClasses);

AnnotatedBeanDefinitionReader.doRegisterBean(…)

<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
			@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {

	// 创建AnnotatedGenericBeanDefinition,这个BeanDefinition包含有注解的元数据信息,即AnnotationMetadata
	// 构造方法中,初始化注解元数据
	AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
	// AnnotatedBeanDefinitionReader的conditionEvaluator在第一步已经创建完毕
	// 根据@Conditional条件等,判断是否应该跳过
	if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
		return;
	}

	abd.setInstanceSupplier(instanceSupplier);
	// 从AnnotationMetadata解析对应的@Scope注解,设置作用域
	ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
	abd.setScope(scopeMetadata.getScopeName());

	// 生成Bean的名称,如果没有,就是类名首字母小写,例如本例中的mainConfig
	String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));

  // 处理常用的注解,有@Lazy、@Primary、@DependsOn、@Role、@Description
	AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
	if (qualifiers != null) {
		for (Class<? extends Annotation> qualifier : qualifiers) {
			if (Primary.class == qualifier) {
				abd.setPrimary(true);
			}
			else if (Lazy.class == qualifier) {
				abd.setLazyInit(true);
			}
			else {
				abd.addQualifier(new AutowireCandidateQualifier(qualifier));
			}
		}
	}
	for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
		customizer.customize(abd);
	}
	// BeanDefinition的持有者,便于操作
	BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
	// 判断是否需要生成代理,如果需要的话,注入两个Bean,一个是targetBeanDefinition,另一个是proxyBeanDefinition
	// 其中proxyBeanDefinition的source指向targetBeanDefinition
	definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
	// 将对应的BeanDefinition注入容器
	BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}

3.AnnotationConfigApplicationContext.refresh()

AbstractApplicationContext.refresh()

@Override
public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		// 准备刷新的上下文环境,设置startupDate,active标志
	  // 同时提供initPropertySources的扩展
		prepareRefresh();

		// 获取创建好的BeanFactory
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

		// 填充属性并注入相关的Bean及BeanPostProcessor
		prepareBeanFactory(beanFactory);

		try {
			// 自行实现,在ApplicationContext标准初始化之前修改它内部的BeanFactory,但是没有实例化任何Bean。
			// 可以在特定的ApplicationContext实现中注册特殊的BeanPostProcessor
			postProcessBeanFactory(beanFactory);

			// 创建并调用BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor的处理方法
			// 其中最重要的是ConfigurationClassPostProcessor中的处理方法
			invokeBeanFactoryPostProcessors(beanFactory);

			// 为BeanFactory创建并注册BeanPostProcessor
			registerBeanPostProcessors(beanFactory);

			// MessageSource:国际化信息支持
			// ApplicationContext本身就是一个MessageSource
			initMessageSource();

			// 创建并初始化事件广播器
			initApplicationEventMulticaster();

			// 自行留给子类实现
			onRefresh();

			// 创建并注册事件监听
			registerListeners();

			// 初始化非懒加载的剩余的Bean
			finishBeanFactoryInitialization(beanFactory);

			// 发布刷新完成事件,通知生命周期处理器lifecycleProcessor刷新过程
			finishRefresh();
		}

		catch (BeansException ex) {
			if (logger.isWarnEnabled()) {
				logger.warn("Exception encountered during context initialization - " +
						"cancelling refresh attempt: " + ex);
			}

			// 发生异常,销毁Bean
			destroyBeans();

			// 重置active标识
			cancelRefresh(ex);

			// Propagate exception to caller.
			throw ex;
		}

		finally {
			// 重置Spring core中的Bean的元数据缓存
			resetCommonCaches();
		}
	}
}

4.invokeBeanFactoryPostProcessors(beanFactory)

AbstractApplicationContext.invokeBeanFactoryPostProcessors

public static void invokeBeanFactoryPostProcessors(
		ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

	
	Set<String> processedBeans = new HashSet<>();
	// 首先调用BeanDefinitionRegistryPostProcessors,参数里面的beanFactoryPostProcessors
	if (beanFactory instanceof BeanDefinitionRegistry) {
		BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
		List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<>();
		List<BeanDefinitionRegistryPostProcessor> registryProcessors = new LinkedList<>();

		for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
			if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
				BeanDefinitionRegistryPostProcessor registryProcessor =
						(BeanDefinitionRegistryPostProcessor) postProcessor;
				registryProcessor.postProcessBeanDefinitionRegistry(registry);
				registryProcessors.add(registryProcessor);
			}
			else {
				regularPostProcessors.add(postProcessor);
			}
		}

		List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
		// 获取并创建手动注册的BeanDefinitionRegistryPostProcessor
		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
				processedBeans.add(ppName);
			}
		}
		// 实现了PriorityOrdered的BeanDefinitionRegistryPostProcessor,排序后再调用
		sortPostProcessors(currentRegistryProcessors, beanFactory);
		registryProcessors.addAll(currentRegistryProcessors);
		// 调用
		invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
		// 清空继续使用
		currentRegistryProcessors.clear();

		// 同上,对于实现了Ordered的BeanDefinitionRegistryPostProcessor,排序后再调用
		postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
		for (String ppName : postProcessorNames) {
			if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
				currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
				processedBeans.add(ppName);
			}
		}
		sortPostProcessors(currentRegistryProcessors, beanFactory);
		registryProcessors.addAll(currentRegistryProcessors);
		invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
		currentRegistryProcessors.clear();

		// 最后,调用所有其余的BeanDefinitionRegistryPostProcessor
		boolean reiterate = true;
		while (reiterate) {
			reiterate = false;
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (!processedBeans.contains(ppName)) {
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
					reiterate = true;
				}
			}
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			currentRegistryProcessors.clear();
		}
		invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
	}

	else {
		// 如果你的容器类型不是BeanDefinitionRegistry,走这里
		invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
	}

	// 然后调用BeanFactoryPostProcessor,和调用BeanDefinitionRegistryPostProcessor类似
	String[] postProcessorNames =
			beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

	List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
	List<String> orderedPostProcessorNames = new ArrayList<>();
	List<String> nonOrderedPostProcessorNames = new ArrayList<>();
	for (String ppName : postProcessorNames) {
		if (processedBeans.contains(ppName)) {
			
		}
		else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
			priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
		}
		else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
			orderedPostProcessorNames.add(ppName);
		}
		else {
			nonOrderedPostProcessorNames.add(ppName);
		}
	}

	// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
	sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
	invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

	// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
	List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
	for (String postProcessorName : orderedPostProcessorNames) {
		orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
	}
	sortPostProcessors(orderedPostProcessors, beanFactory);
	invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

	// Finally, invoke all other BeanFactoryPostProcessors.
	List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
	for (String postProcessorName : nonOrderedPostProcessorNames) {
		nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
	}
	invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

	// Clear cached merged bean definitions since the post-processors might have
	// modified the original metadata, e.g. replacing placeholders in values...
	beanFactory.clearMetadataCache();
}

5.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry()方法

ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry()

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
	//生成唯一标识,用于重复处理验证
	int registryId = System.identityHashCode(registry);
	if (this.registriesPostProcessed.contains(registryId)) {
		throw new IllegalStateException(
					"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
	}
	if (this.factoriesPostProcessed.contains(registryId)) {
		throw new IllegalStateException(
					"postProcessBeanFactory already called on this post-processor against " + registry);
	}
	this.registriesPostProcessed.add(registryId);
	// 解析Java类配置bean
	processConfigBeanDefinitions(registry);
}

processConfigBeanDefinitions()

public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
   List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
	  //所有已经注册的bean,此时并没有解析,容器里只有默认初始化的Bean
	String[] candidateNames = registry.getBeanDefinitionNames();
	//遍历bean定义信息,
	for (String beanName : candidateNames) {
		BeanDefinition beanDef = registry.getBeanDefinition(beanName);
		if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
					ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
				}
		}
	  // 如果当前的bean是Javabean配置类(含有@Configuration注解的类),则加入到集合configCandidates中,
		// 除此之外,包括上面的代码,都提到了@Bean注入的两种模式,Full和Lite模式,在第三篇文章有介绍,源码中也有详细说明这两种模式
		else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
				configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
		}
	}

  // 没有@Configuration注解的类,直接退出
	if (configCandidates.isEmpty()) {
		return;
	}

	// 多个Java配置类,按@Ordered注解排序
	configCandidates.sort((bd1, bd2) -> {
		int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
		int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
		return Integer.compare(i1, i2);
	});

	// 我们的DefaultListableFactory就是SingletonBeanRegistry
	// 但是此时我们的容器里面并没有这个BeanNameGenerator,所有generator为null
	SingletonBeanRegistry sbr = null;
	if (registry instanceof SingletonBeanRegistry) {
		sbr = (SingletonBeanRegistry) registry;
		if (!this.localBeanNameGeneratorSet) {
				BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
				if (generator != null) {
					this.componentScanBeanNameGenerator = generator;
					this.importBeanNameGenerator = generator;
				}
		}
	}

	if (this.environment == null) {
		this.environment = new StandardEnvironment();
	}

  // 初始化一个ConfigurationClassParser解析器,可以解析@Congiguration配置类
	ConfigurationClassParser parser = new ConfigurationClassParser(
				this.metadataReaderFactory, this.problemReporter, this.environment,
				this.resourceLoader, this.componentScanBeanNameGenerator, registry);

	Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
	Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
	do {
	 // 解析Java配置类
		parser.parse(candidates);
	 // 主要校验配置类不能使用final修饰符(CGLIB代理是生成一个子类,因此原先的类不能使用final修饰)
		parser.validate();

		//排除已处理过的配置类
		Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
		configClasses.removeAll(alreadyParsed);
			
		// Read the model and create bean definitions based on its content
		if (this.reader == null) {
				this.reader = new ConfigurationClassBeanDefinitionReader(
							registry, this.sourceExtractor, this.resourceLoader, this.environment,
							this.importBeanNameGenerator, parser.getImportRegistry());
		}
	 // 加载bean定义信息,主要实现将@bean @Configuration @Import @ImportResource @ImportRegistrar注册为bean
		this.reader.loadBeanDefinitions(configClasses);
		alreadyParsed.addAll(configClasses);
		// 清空已处理的配置类
		candidates.clear();
	 // 再次获取容器中bean定义数量  如果大于 之前获取的bean定义数量,则说明有新的bean注册到容器中,需要再次解析
		if (registry.getBeanDefinitionCount() > candidateNames.length) {
				String[] newCandidateNames = registry.getBeanDefinitionNames();
				Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
				Set<String> alreadyParsedClasses = new HashSet<>();
				for (ConfigurationClass configurationClass : alreadyParsed) {
					alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
				}
				for (String candidateName : newCandidateNames) {
					if (!oldCandidateNames.contains(candidateName)) {
							BeanDefinition bd = registry.getBeanDefinition(candidateName);
	       // 新注册的bean如果也是@Configuration配置类,则添加到数据,等待解析
							if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
										!alreadyParsedClasses.contains(bd.getBeanClassName())) {
								candidates.add(new BeanDefinitionHolder(bd, candidateName));
							}
					}
				}
				candidateNames = newCandidateNames;
		}
	}
	while (!candidates.isEmpty());

	// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
	if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
		sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
	}

	if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
		// Clear cache in externally provided MetadataReaderFactory; this is a no-op
		// for a shared cache since it'll be cleared by the ApplicationContext.
		((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
	}
}

解析Java配置类parser.parse(candidates)

protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
  //判断是否需要解析
   if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
      return;
   }
   //判断同一个配置类是否重复加载过,如果重复加载过,则合并,否则从集合中移除旧的配置类,后续逻辑将处理新的配置类
   ConfigurationClass existingClass = this.configurationClasses.get(configClass);
   if (existingClass != null) {
      if (configClass.isImported()) {
         if (existingClass.isImported()) {
            existingClass.mergeImportedBy(configClass);
         }
         // Otherwise ignore new imported config class; existing non-imported class overrides it.
         return;
      }
      else {
         // Explicit bean definition found, probably replacing an import.
         // Let's remove the old one and go with the new one.
         this.configurationClasses.remove(configClass);
         this.knownSuperclasses.values().removeIf(configClass::equals);
      }
   }

   // Recursively process the configuration class and its superclass hierarchy.
   SourceClass sourceClass = asSourceClass(configClass);
   do {
     //【真正解析配置类】
      sourceClass = doProcessConfigurationClass(configClass, sourceClass);
   }
   while (sourceClass != null);
   // 再次添加到到集合中
   this.configurationClasses.put(configClass, configClass);
}

ConfigurationClassParser. doProcessConfigurationClass()

protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
      throws IOException {

   // 递归处理任何成员(嵌套)类
   processMemberClasses(configClass, sourceClass);

   // 处理@PropertySource注解
   for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
         sourceClass.getMetadata(), PropertySources.class,
         org.springframework.context.annotation.PropertySource.class)) {
      if (this.environment instanceof ConfigurableEnvironment) {
         processPropertySource(propertySource);
      }
      else {
         logger.warn("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
               "]. Reason: Environment must implement ConfigurableEnvironment");
      }
   }

   // 处理@ComponentScan 
   // 获取@ComponentScan注解信息
   Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
         sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
   if (!componentScans.isEmpty() &&
         !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
      for (AnnotationAttributes componentScan : componentScans) {

         // 按@CmponentScan注解扫描bean
         Set<BeanDefinitionHolder> scannedBeanDefinitions =
               this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
         // 遍历扫描出的bean定义是否是配置类bean
         for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
            BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
            if (bdCand == null) {
               bdCand = holder.getBeanDefinition();
            }
            // 如果扫描出的bean定义是配置类(含有@COnfiguration),则继续调用parse方法,内部再次调用doProcessConfigurationClas(),递归解析
            if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
               parse(bdCand.getBeanClassName(), holder.getBeanName());
            }
         }
      }
   }

   // 处理@Import注解
   processImports(configClass, sourceClass, getImports(sourceClass), true);

   // 处理@ImportResource注解
   AnnotationAttributes importResource = AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
   if (importResource != null) {
      String[] resources = importResource.getStringArray("locations");
      Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
      for (String resource : resources) {
         String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
         configClass.addImportedResource(resolvedResource, readerClass);
      }
   }

   // 处理@Bean注解 
   Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
   for (MethodMetadata methodMetadata : beanMethods) {
      // 将解析出的所有@Bean注解方法添加到configClass配置类信息中
      configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
   }

   // 处理接口中所有添加@Bean注解的方法,内部通过遍历所有接口,解析得到@Bean注解方法,并添加到configClass配置类信息中
   processInterfaces(configClass, sourceClass);

   // 如果有父类,则返回父类,递归执行doProcessConfigurationClass()解析父类
   if (sourceClass.getMetadata().hasSuperClass()) {
      String superclass = sourceClass.getMetadata().getSuperClassName();
      if (superclass != null && !superclass.startsWith("java") &&
            !this.knownSuperclasses.containsKey(superclass)) {
         this.knownSuperclasses.put(superclass, configClass);
         // Superclass found, return its annotation metadata and recurse
         return sourceClass.getSuperClass();
      }
   }

   // No superclass -> processing is complete
   return null;
}

6.@Bean和@ComponentScan的解析过程

6.1 @ComponentScan注解解析过程

Set<BeanDefinitionHolder> scannedBeanDefinitions =  this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());

ClassPathBeanDefinitionScanner.parse(…)

public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
   ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
         componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);

   Class<? extends BeanNameGenerator> generatorClass = componentScan.getClass("nameGenerator");
   boolean useInheritedGenerator = (BeanNameGenerator.class == generatorClass);
   scanner.setBeanNameGenerator(useInheritedGenerator ? this.beanNameGenerator :
         BeanUtils.instantiateClass(generatorClass));
	// @ComponentScan注解scopedProxy属性的处理
   ScopedProxyMode scopedProxyMode = componentScan.getEnum("scopedProxy");
   if (scopedProxyMode != ScopedProxyMode.DEFAULT) {
      scanner.setScopedProxyMode(scopedProxyMode);
   }
   else {
      Class<? extends ScopeMetadataResolver> resolverClass = componentScan.getClass("scopeResolver");
      scanner.setScopeMetadataResolver(BeanUtils.instantiateClass(resolverClass));
   }

   scanner.setResourcePattern(componentScan.getString("resourcePattern"));
	// @ComponentScan注解filter属性的处理
   for (AnnotationAttributes filter : componentScan.getAnnotationArray("includeFilters")) {
      for (TypeFilter typeFilter : typeFiltersFor(filter)) {
         scanner.addIncludeFilter(typeFilter);
      }
   }
   for (AnnotationAttributes filter : componentScan.getAnnotationArray("excludeFilters")) {
      for (TypeFilter typeFilter : typeFiltersFor(filter)) {
         scanner.addExcludeFilter(typeFilter);
      }
   }
	// @ComponentScan注解懒加载的处理
   boolean lazyInit = componentScan.getBoolean("lazyInit");
   if (lazyInit) {
      scanner.getBeanDefinitionDefaults().setLazyInit(true);
   }

   Set<String> basePackages = new LinkedHashSet<>();
	 // @ComponentScan注解扫描包的处理
   String[] basePackagesArray = componentScan.getStringArray("basePackages");
   for (String pkg : basePackagesArray) {
      String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg),
            ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
      Collections.addAll(basePackages, tokenized);
   }
   for (Class<?> clazz : componentScan.getClassArray("basePackageClasses")) {
      basePackages.add(ClassUtils.getPackageName(clazz));
   }
	 // 如果没有指定扫描包,把当前类所在的包加进去
   if (basePackages.isEmpty()) {
      basePackages.add(ClassUtils.getPackageName(declaringClass));
   }

   scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {
      @Override
      protected boolean matchClassName(String className) {
         return declaringClass.equals(className);
      }
   });
	 // 根据需要扫描的包,进行逐个扫描
   return scanner.doScan(StringUtils.toStringArray(basePackages));
}

ClassPathBeanDefinitionScanner.doScan(…)

protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
	Assert.notEmpty(basePackages, "At least one base package must be specified");
	Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
	for (String basePackage : basePackages) {
    // 根据basePackage加载包下所有java文件,并扫描出所有bean组件    
		Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
    // 遍历beandefition
		for (BeanDefinition candidate : candidates) {
     // 解析作用域Scope
				ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
				candidate.setScope(scopeMetadata.getScopeName());
				String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
				if (candidate instanceof AbstractBeanDefinition) {
					postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
				}
     // 通用注解解析到candidate结构中,主要是处理Lazy, primary DependsOn, Role ,Description这五个注解
				if (candidate instanceof AnnotatedBeanDefinition) {
					AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
				}
      // 检查当前bean是否已经注册,不存在则注册
				if (checkCandidate(beanName, candidate)) {
					BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
					definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
					beanDefinitions.add(definitionHolder);
     // 注册到ioc容器中,主要是一些@Component组件,@Bean注解方法并没有在此处注册,beanname和beandefinition 键值对
					registerBeanDefinition(definitionHolder, this.registry);
				}
		}
	}
	return beanDefinitions;
}

ClassPathScanningCandidateComponentProvider.scanCandidateComponents(…)

private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
	Set<BeanDefinition> candidates = new LinkedHashSet<>();
	try {
		String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
					resolveBasePackage(basePackage) + '/' + this.resourcePattern;
   // 获取当前包下所有的class文件
		Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
		boolean traceEnabled = logger.isTraceEnabled();
		boolean debugEnabled = logger.isDebugEnabled();
		for (Resource resource : resources) {
				if (traceEnabled) {
					logger.trace("Scanning " + resource);
				}
				if (resource.isReadable()) {
					try {
							MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
         // 按照scanner过滤器过滤,比如配置类本身将被过滤掉,没有@Component等组件注解的类将过滤掉
							// 包含@Component注解的组件将创建BeanDefinition
							if (isCandidateComponent(metadataReader)) {
								ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
								sbd.setResource(resource);
								sbd.setSource(resource);
								if (isCandidateComponent(sbd)) {
										if (debugEnabled) {
											logger.debug("Identified candidate component class: " + resource);
										}
										candidates.add(sbd);
								}
								else {
										if (debugEnabled) {
											logger.debug("Ignored because not a concrete top-level class: " + resource);
										}
								}
							} else {
								if (traceEnabled) {
										logger.trace("Ignored because not matching any filter: " + resource);
								}
							}
					}
					catch (Throwable ex) {
							throw new BeanDefinitionStoreException(
										"Failed to read candidate component class: " + resource, ex);
					}
				}
				else {
					if (traceEnabled) {
							logger.trace("Ignored because not readable: " + resource);
					}
				}
		}
	}
	catch (IOException ex) {
		throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
	}
	return candidates;
}

6.2 @Bean注解解析过程

ConfigurationClassParser.retrieveBeanMethodMetadata(…)

private Set<MethodMetadata> retrieveBeanMethodMetadata(SourceClass sourceClass) {
	AnnotationMetadata original = sourceClass.getMetadata();
	// 获取所有@Bean注解的方法
	Set<MethodMetadata> beanMethods = original.getAnnotatedMethods(Bean.class.getName());
	// 如果配置类中有多个@Bean注解的方法,则排序
	if (beanMethods.size() > 1 && original instanceof StandardAnnotationMetadata) {
		// Try reading the class file via ASM for deterministic declaration order...
		// Unfortunately, the JVM's standard reflection returns methods in arbitrary
		// order, even between different runs of the same application on the same JVM.
		try {
				AnnotationMetadata asm =
							this.metadataReaderFactory.getMetadataReader(original.getClassName()).getAnnotationMetadata();
				Set<MethodMetadata> asmMethods = asm.getAnnotatedMethods(Bean.class.getName());
				if (asmMethods.size() >= beanMethods.size()) {
					Set<MethodMetadata> selectedMethods = new LinkedHashSet<>(asmMethods.size());
					for (MethodMetadata asmMethod : asmMethods) {
							for (MethodMetadata beanMethod : beanMethods) {
								if (beanMethod.getMethodName().equals(asmMethod.getMethodName())) {
										selectedMethods.add(beanMethod);
										break;
								}
							}
					}
					if (selectedMethods.size() == beanMethods.size()) {
							// All reflection-detected methods found in ASM method set -> proceed
							beanMethods = selectedMethods;
					}
				}
		}
		catch (IOException ex) {
				logger.debug("Failed to read class file via ASM for determining @Bean method order", ex);
				// No worries, let's continue with the reflection metadata we started with...
		}
	}
	return beanMethods;
}

7.加载bean定义信息this.reader.loadBeanDefinitions(configClasses)

??回到ConfigurationClassPostProcessor#processConfigBeanDefinitions方法,当调用完parse方法之后,能得到一批ConfigurationClass集合,但是这时候只是获取到,而容器中还没有对应的注册信息,那么接下来就是对这批集合进行注册处理

??ConfigurationClassBeanDefinitionReader.loadBeanDefinitions()方法的功能就是将之前解析出的configClasses配置类信息中所有配置相关的信息添加到spring的bean定义,主要是配置类中的@Bean注解方法,配置类@ImportResource和@Import(实现ImportBeanDefinitionRegistrar接口方式)的bean注册

ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(…)

private void loadBeanDefinitionsForConfigurationClass(
	ConfigurationClass configClass, TrackedConditionEvaluator trackedConditionEvaluator) {
	if (trackedConditionEvaluator.shouldSkip(configClass)) {
	String beanName = configClass.getBeanName();
	if (StringUtils.hasLength(beanName) && this.registry.containsBeanDefinition(beanName)) {
			this.registry.removeBeanDefinition(beanName);
	}
	this.importRegistry.removeImportingClass(configClass.getMetadata().getClassName());
	return;
}
// 与@Import注解相关
if (configClass.isImported()) {
	registerBeanDefinitionForImportedConfigurationClass(configClass);
}
  // 将@Bean方法注册为bean
for (BeanMethod beanMethod : configClass.getBeanMethods()) {
	loadBeanDefinitionsForBeanMethod(beanMethod);
}
// 将configClass中中ImportResource指定的资源注册为bean
loadBeanDefinitionsFromImportedResources(configClass.getImportedResources());
// 将configClass中ImportedRegistrar注册为bean
loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());
}

ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod(…)

private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) {
	ConfigurationClass configClass = beanMethod.getConfigurationClass();
	MethodMetadata metadata = beanMethod.getMetadata();
	// 获取方法名
	String methodName = metadata.getMethodName();

	// Do we need to mark the bean as skipped by its condition?
	if (this.conditionEvaluator.shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN)) {
			configClass.skippedBeanMethods.add(methodName);
			return;
	}
	if (configClass.skippedBeanMethods.contains(methodName)) {
			return;
	}

	// 获取@Bean注解的元数据信息
	AnnotationAttributes bean = AnnotationConfigUtils.attributesFor(metadata, Bean.class);
	Assert.state(bean != null, "No @Bean annotation attributes");

	// Consider name and any aliases
	// 获取@Bean注解是否有name属性,如@Bean(name = "myBean")
	List<String> names = new ArrayList<>(Arrays.asList(bean.getStringArray("name")));
	// 默认bean的名称和方法名称相同,但是如果设置了name,就取name作为beanName
	String beanName = (!names.isEmpty() ? names.remove(0) : methodName);

	// 创建一个BeanMethod的BeanDefinition
	ConfigurationClassBeanDefinition beanDef = new ConfigurationClassBeanDefinition(configClass, metadata);
	beanDef.setResource(configClass.getResource());
	beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource()));

	// 设置工厂方法
	// 后期Bean的实例化,getBean的时候,会判断BeanMethod是否存在FactoryMethod,如果存在,就使用反射调用工厂方法,返回工厂方法中的对象
	if (metadata.isStatic()) {
			// static @Bean method
			beanDef.setBeanClassName(configClass.getMetadata().getClassName());
			beanDef.setFactoryMethodName(methodName);
	}
	else {
			// instance @Bean method
			beanDef.setFactoryBeanName(configClass.getBeanName());
			beanDef.setUniqueFactoryMethodName(methodName);
	}
	// ....
	this.registry.registerBeanDefinition(beanName, beanDefToRegister);
}

??上面只列出了核心代码,主要是构造了BeanDefinition,然后注册进容器,而BeanDefinition的一些属性则是由注解中获取,这部分代码省略。

??另外,可以看到@Bean的方式构造的BeanDefinition的时候,与普通的不同,这种方式是会设置工厂方法去初始化,也就是说,AppConfig 类下的appBean方法被Spring当成一个工厂方法,也就是说这种方式与下列的初始化方式原理类似:

<bean id="appConfig" class="com.example.springboot.springbootdemo.bean.AppConfig"/>

<bean id="appBean" factory-bean="appConfig" factory-method="appBean"></bean>

小结

引用:Spring启动流程图

??处理逻辑理了一遍后,看一下ConfigurationClassPostProcessor处理器解析@configuration配置类主要过程:

  • 1.Spring容器初始化时注册默认后置处理器ConfigurationClassPostProcessor

  • 2.Spring容器初始化执行refresh()方法中调用ConfigurationClassPostProcessor

  • 3.ConfigurationClassPostProcessor处理器借助ConfigurationClassParser完成配置类解析

  • 4.ConfigurationClassParser配置内解析过程中完成嵌套的MemberClass、@PropertySource注解、@ComponentScan注解(扫描package下的所有Class并进行迭代解析,主要是@Component组件解析及注册)、@ImportResource、@Bean等处理

  • 5.完成@Bean注册, @ImportResource指定bean的注册以及@Import(实现ImportBeanDefinitionRegistrar接口方式)的bean注册

  • 6.有@Bean注解的方法在解析的时候作为ConfigurationClass的一个属性,最后还是会转换成BeanDefinition进行处理, 而实例化的时候会作为一个工厂方法进行Bean的创建

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-05-24 17:59:01  更:2022-05-24 18:02:42 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 20:17:31-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码