Mr. Cappuccino’s 63rd cup of coffee—Spring’s AnnotationConfigApplicationContext source code analysis

Spring's AnnotationConfigApplicationContext source code analysis

Source code analysis

Source code analysis of the code from the previous article "Spring Bean Life Cycle"

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();

new AnnotationConfigApplicationContext(SpringConfig02.class)

AnnotationConfigApplicationContext.java

Insert image description here

AbstractApplicationContext.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();
		}
	}
}

Two important objects in BeanFactory

DefaultListableBeanFactory.java

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

DefaultSingletonBeanRegistry.java

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

Debug source code analysis

Insert image description here
Insert image description here

register(componentClasses): Register the specified configuration class SpringConfig02 into the beanDefinitionMap collection

Insert image description here

Insert image description here

Insert image description here

Insert image description here

invokeBeanFactoryPostProcessors(beanFactory): Create an instance object of the implementation class related to the BeanFactoryPostProcessor interface and store it in the singletonObjects collection; execute the method of the implementation class related to the BeanFactoryPostProcessor interface, process the bean objects that need to be registered in the configuration class through ConfigurationClassPostProcessor, and register the bean object to the beanDefinitionMap collection middle.

Insert image description here

registerBeanPostProcessors(beanFactory): Register the implementation class related to the BeanPostProcessor interface, create an instance object of the implementation class related to the BeanPostProcessor interface and store it in the singletonObjects collection

Insert image description here
Insert image description here

finishBeanFactoryInitialization(beanFactory): Instantiate and initialize the remaining non-lazy loading singleton objects and store them in the singletonObjects collection

Insert image description here

beanFactory.preInstantiateSingletons(): Load singleton objects in advance


Guess you like

Origin blog.csdn.net/sinat_41888963/article/details/132280191