Mr. Cappuccino的第63杯咖啡——Spring之AnnotationConfigApplicationContext源码分析

Spring之AnnotationConfigApplicationContext源码分析

源码分析

以上一篇文章《Spring之Bean的生命周期》的代码进行源码分析

java 复制代码
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig02.class);
LifeCycleBean lifeCycleBean = applicationContext.getBean("lifeCycleBean", LifeCycleBean.class);
System.out.println("-----------------------------------");
System.out.println("LifeCycleBean " + lifeCycleBean);
System.out.println("-----------------------------------");
applicationContext.close();

java 复制代码
new AnnotationConfigApplicationContext(SpringConfig02.class)

AnnotationConfigApplicationContext.java

AbstractApplicationContext.java

java 复制代码
@Override
public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		// Prepare this context for refreshing.
		// 容器刷新前的准备工作,例如对系统属性、环境变量进行准备及验证
		prepareRefresh();

		// Tell the subclass to refresh the internal bean factory.
		// 初始化BeanFactory
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

		// Prepare the bean factory for use in this context.
		// 对BeanFactory进行属性填充及功能填充,例如添加某些BeanPostProcessor以实现某些功能(ApplicationContextAwareProcessor)
		prepareBeanFactory(beanFactory);

		try {
			// Allows post-processing of the bean factory in context subclasses.
			// 空方法,用于子类实现扩展功能
			postProcessBeanFactory(beanFactory);

			// Invoke factory processors registered as beans in the context.
			// 执行BeanFactoryPostProcessor,例如ConfigurationClassPostProcessor、EventListenerMethodProcessor以及某些自定义的BeanFactoryPostProcessor
			// ConfigurationClassPostProcessor用于处理配置类,会将配置类中需要注册的Bean对象的元数据解析并存入beanDefinitionMap集合中
			invokeBeanFactoryPostProcessors(beanFactory);

			// Register bean processors that intercept bean creation.
			// 注册BeanPostProcessor,例如AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor以及某些自定义的BeanPostProcessor
			registerBeanPostProcessors(beanFactory);

			// Initialize message source for this context.
			// 初始化消息资源,国际化处理
			initMessageSource();

			// Initialize event multicaster for this context.
			// 初始化消息多播器
			initApplicationEventMulticaster();

			// Initialize other special beans in specific context subclasses.
			// 空方法,用于子类实现扩展功能
			onRefresh();

			// Check for listener beans and register them.
			// 注册所有的ApplicationListener到消息多播器
			registerListeners();

			// Instantiate all remaining (non-lazy-init) singletons.
			// 实例化、初始化剩下的非懒加载的单例对象
			finishBeanFactoryInitialization(beanFactory);

			// Last step: publish corresponding event.
			// 完成刷新动作,启动LifecycleProcessor,发布ContextRefreshedEvent事件
			finishRefresh();
		}

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

			// Destroy already created singletons to avoid dangling resources.
			// 销毁已创建的单例对象
			destroyBeans();

			// Reset 'active' flag.
			cancelRefresh(ex);

			// Propagate exception to caller.
			throw ex;
		}

		finally {
			// Reset common introspection caches in Spring's core, since we
			// might not ever need metadata for singleton beans anymore...
			resetCommonCaches();
		}
	}
}

BeanFactory中两个重要的对象

DefaultListableBeanFactory.java

java 复制代码
/** Map of bean definition objects, keyed by bean name. */
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);

DefaultSingletonBeanRegistry.java

java 复制代码
/** Cache of singleton objects: bean name to bean instance. */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

Debug源码分析


register(componentClasses):注册指定的配置类SpringConfig02到beanDefinitionMap集合中

invokeBeanFactoryPostProcessors(beanFactory):创建BeanFactoryPostProcessor接口相关实现类的实例对象并存入singletonObjects集合中;执行BeanFactoryPostProcessor接口相关实现类的方法,通过ConfigurationClassPostProcessor处理配置类中需要注册的bean对象,并将bean对象注册到beanDefinitionMap集合中。

registerBeanPostProcessors(beanFactory):注册BeanPostProcessor接口相关实现类,创建BeanPostProcessor接口相关实现类的实例对象并存入singletonObjects集合中


finishBeanFactoryInitialization(beanFactory):实例化、初始化剩下的非懒加载的单例对象并存入singletonObjects集合中

beanFactory.preInstantiateSingletons():提前加载单例对象


相关推荐
刘新明19895 分钟前
Frida辅助分析OLLVM虚假控制流程(下)
java·开发语言·前端
第二只羽毛27 分钟前
重载和继承的实践
java·开发语言
王嘉俊92532 分钟前
设计模式--适配器模式:优雅解决接口不兼容问题
java·设计模式·适配器模式
王嘉俊92533 分钟前
设计模式--组合模式:统一处理树形结构的优雅设计
java·设计模式·组合模式
道199340 分钟前
50 台小型无人车与50套穿戴终端 5 公里范围内通信组网方案深度研究
java·后端·struts
迎風吹頭髮1 小时前
UNIX下C语言编程与实践35-UNIX 守护进程编写:后台执行、脱离终端、清除掩码与信号处理
java·c语言·unix
光军oi1 小时前
全栈开发杂谈————JAVA微服务全套技术栈详解
java·开发语言·微服务
帮帮志1 小时前
目录【系列文章目录】-(关于帮帮志,关于作者)
java·开发语言·python·链表·交互
聪明的笨猪猪1 小时前
Java Spring “MVC ”面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
Boop_wu2 小时前
[数据结构] Map和Set
java·数据结构·算法