7.Java Spring框架源码分析-IOC-创建spring容器

目录

  • [1. 要分析的代码](#1. 要分析的代码)
  • [2. 创建ApplicationContext](#2. 创建ApplicationContext)
    • [2.1. AnnotationConfigApplicationContext构造方法](#2.1. AnnotationConfigApplicationContext构造方法)
    • [2.2. 刷新ioc容器](#2.2. 刷新ioc容器)
      • [2.2.1. 准备刷新](#2.2.1. 准备刷新)
      • [2.2.2. 获取刷新后的BeanFactory](#2.2.2. 获取刷新后的BeanFactory)
      • [2.2.3. 准备BeanFactory](#2.2.3. 准备BeanFactory)
      • [2.2.4. 调用BeanFactoryPostProcessor的postProcess方法](#2.2.4. 调用BeanFactoryPostProcessor的postProcess方法)
      • [2.2.5. 注册BeanPostProcessor](#2.2.5. 注册BeanPostProcessor)
      • [2.2.6. 初始化国际化相关的bean](#2.2.6. 初始化国际化相关的bean)
      • [2.2.7. 初始化事件派发器](#2.2.7. 初始化事件派发器)
      • [2.2.8. 注册事件监听器到事件派发器中](#2.2.8. 注册事件监听器到事件派发器中)
      • [2.2.9. 完成BeanFactory的初始化](#2.2.9. 完成BeanFactory的初始化)
      • [2.2.10. 完成刷新](#2.2.10. 完成刷新)
        • [2.2.10.1. 初始化生命周期有关的PostProcessor](#2.2.10.1. 初始化生命周期有关的PostProcessor)

1. 要分析的代码

java 复制代码
public static void main(String[] args)
{
    //创建ApplicationContext
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AopConfig.class);
    //从ApplicationContext中获取Calc的bean
    Calc calc = applicationContext.getBean(Calc.class);
    //调用div方法
    System.out.println(calc.div(10,10));

}

分成创建ApplicationContext和从ApplicationContext中获取Calc的bean这两个过程,我们一步步跟踪

2. 创建ApplicationContext

2.1. AnnotationConfigApplicationContext构造方法

java 复制代码
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
	//调用无参构造方法
	this();
	//注册主配置类
	register(annotatedClasses);
	//刷新ioc容器
	refresh();
}

refresh方法用于刷新容器,这是我们分析的重点,他会调用AnnotationConfigApplicationContext的父类AbstractApplicationContext的refresh方法。

2.2. 刷新ioc容器

  • AbstractApplicationContext refresh
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.
	//获取bean工厂
	ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

	// Prepare the bean factory for use in this context.
	//为bean工厂初始化一些属性,加入一些BeanPostProcessor
	prepareBeanFactory(beanFactory);

	try {
		// Allows post-processing of the bean factory in context subclasses.
		//在bean工厂创建完后做一些事情。留给子类实现(模板方法)
		postProcessBeanFactory(beanFactory);

		// Invoke factory processors registered as beans in the context.
		//按优先级顺序调用BeanFactoryPostProcessor的postProcessBeanFactory方法
		invokeBeanFactoryPostProcessors(beanFactory);

		// Register bean processors that intercept bean creation.
		//把所有BeanPostProcessor注册到bean工厂
		registerBeanPostProcessors(beanFactory);

		// Initialize message source for this context.
		//初始化国际化相关的bean
		initMessageSource();

		// Initialize event multicaster for this context.
		//初始化事件派发器
		initApplicationEventMulticaster();

		// Initialize other special beans in specific context subclasses.
		//留给子类实现(模板方法)
		onRefresh();

		// Check for listener beans and register them.
		//注册事件监听器到事件派发器中
		registerListeners();

		// Instantiate all remaining (non-lazy-init) singletons.
		//实例化所有剩下的非懒加载的单例
		finishBeanFactoryInitialization(beanFactory);

		// Last step: publish corresponding event.
		finishRefresh();
	}

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

		// Destroy already  
		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();
	}
}
}

2.2.1. 准备刷新

  • AbstractApplicationContext prepareRefresh
java 复制代码
protected void prepareRefresh() {
	// 启动时间,active标志
	this.startupDate = System.currentTimeMillis();
	this.closed.set(false);
	this.active.set(true);

	if (logger.isInfoEnabled()) {
		logger.info("Refreshing " + this);
	}

	// Initialize any placeholder property sources in the context environment.
	//初始化占位符属性。模板方法(留给子类实现)
	initPropertySources();

	// Validate that all properties marked as required are resolvable:
	// see ConfigurablePropertyResolver#setRequiredProperties
	//校验属性
	getEnvironment().validateRequiredProperties();

	// Allow for the collection of early ApplicationEvents,
	// to be published once the multicaster is available...
	//保存早期的事件。后面用于事件分发
	this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>();
}

准备刷新的工作没什么说的,如注释。其中initPropertySources这个初始化占位符属性的操作留给子类实现

2.2.2. 获取刷新后的BeanFactory

  • AbstractApplicationContext obtainFreshBeanFactory
java 复制代码
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
	//刷新bean工厂。模板方法(留给子类实现)
	refreshBeanFactory();
	//获取bean工厂并且返回--什么时候创建的?
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	if (logger.isDebugEnabled()) {
		logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
	}
	return beanFactory;
}

refreshBeanFactory这个刷新BeanFactory的操作又是留给子类实现

2.2.3. 准备BeanFactory

  • AbstractApplicationContext prepareBeanFactory
java 复制代码
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	// Tell the internal bean factory to use the context's class loader etc.
	//设置类加载器等
	beanFactory.setBeanClassLoader(getClassLoader());
	beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

	// Configure the bean factory with context callbacks.
	//为bean工厂加入PostProcessor:ApplicationContextAwareProcessor->用于ApplicationContextAware,忽略一些依赖等
	beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
	beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
	beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
	beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
	beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

	// BeanFactory interface not registered as resolvable type in a plain factory.
	// MessageSource registered (and found for autowiring) as a bean.
	//
	beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
	beanFactory.registerResolvableDependency(ResourceLoader.class, this);
	beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
	beanFactory.registerResolvableDependency(ApplicationContext.class, this);

	// Register early post-processor for detecting inner beans as ApplicationListeners.
	//为bean工厂加入PostProcessor:ApplicationListenerDetector--用于事件监听
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

	// Detect a LoadTimeWeaver and prepare for weaving, if found.
	//为bean工厂加入PostProcessor:LoadTimeWeaverAwareProcessor--用于切面
	if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		// Set a temporary ClassLoader for type matching.
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}

	// Register default environment beans.
	//注册环境相关的beans
	if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
	}
}

这个准备就是往BeanFactory中注入一些PostProcessor

2.2.4. 调用BeanFactoryPostProcessor的postProcess方法

  • AbstractApplicationContext invokeBeanFactoryPostProcessors
java 复制代码
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
	//把当前bean工厂,所有的bean工厂PostProcessors传入
	PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

	// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
	// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
	if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}
}

这个操作比较关键,详见2.调用BeanFactoryPostProcessor的postProcess方法.md

2.2.5. 注册BeanPostProcessor

  • AbstractApplicationContext registerBeanPostProcessors
java 复制代码
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
	//传入当前bean工厂
	PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}

这个操作比较关键,详见下面的3.注册BeanPostProcessor.md

2.2.6. 初始化国际化相关的bean

  • initMessageSource
java 复制代码
protected void initMessageSource() {
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	//从bean工厂中获取messageSource
	if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
		this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
		// Make MessageSource aware of parent MessageSource.
		if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
			HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
			if (hms.getParentMessageSource() == null) {
				// Only set parent context as parent MessageSource if no parent MessageSource
				// registered already.
				hms.setParentMessageSource(getInternalParentMessageSource());
			}
		}
		if (logger.isDebugEnabled()) {
			logger.debug("Using MessageSource [" + this.messageSource + "]");
		}
	}
	//获取不到的话
	else {
		// Use empty MessageSource to be able to accept getMessage calls.
		//创建一个默认的DelegatingMessageSource
		DelegatingMessageSource dms = new DelegatingMessageSource();
		dms.setParentMessageSource(getInternalParentMessageSource());
		this.messageSource = dms;
		//并注册进入bean工厂
		beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
		if (logger.isDebugEnabled()) {
			logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME +
					"': using default [" + this.messageSource + "]");
		}
	}
}

2.2.7. 初始化事件派发器

  • initApplicationEventMulticaster
java 复制代码
protected void initApplicationEventMulticaster() {
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	//从bean工厂中获取名为applicationEventMulticaster的bean(事件派发器)
	if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
		this.applicationEventMulticaster =
				beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
		if (logger.isDebugEnabled()) {
			logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
		}
	}
	//获取不到
	else {
		//创建一个SimpleApplicationEventMulticaster并注册进bean工厂
		this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
		beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
		if (logger.isDebugEnabled()) {
			logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
					APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
					"': using default [" + this.applicationEventMulticaster + "]");
		}
	}
}

2.2.8. 注册事件监听器到事件派发器中

  • registerListeners
java 复制代码
protected void registerListeners() {
	// Register statically specified listeners first.
	//获取所有的事件监听器,放入事件派发器中
	for (ApplicationListener<?> listener : getApplicationListeners()) {
		getApplicationEventMulticaster().addApplicationListener(listener);
	}

	// Do not initialize FactoryBeans here: We need to leave all regular beans
	// uninitialized to let post-processors apply to them!
	//从bean工厂中获取类型为ApplicationListener的所有bean,放入事件派发器中
	String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
	for (String listenerBeanName : listenerBeanNames) {
		getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
	}

	// Publish early application events now that we finally have a multicaster...
	//获取早期的事件,使用事件派发器分派
	Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
	this.earlyApplicationEvents = null;
	if (earlyEventsToProcess != null) {
		for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
			getApplicationEventMulticaster().multicastEvent(earlyEvent);
		}
	}
}

2.2.9. 完成BeanFactory的初始化

  • finishBeanFactoryInitialization
java 复制代码
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	// Initialize conversion service for this context.
	if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
			beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
		beanFactory.setConversionService(
				beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
	}

	// Register a default embedded value resolver if no bean post-processor
	// (such as a PropertyPlaceholderConfigurer bean) registered any before:
	// at this point, primarily for resolution in annotation attribute values.
	if (!beanFactory.hasEmbeddedValueResolver()) {
		beanFactory.addEmbeddedValueResolver(new StringValueResolver() {
			@Override
			public String resolveStringValue(String strVal) {
				return getEnvironment().resolvePlaceholders(strVal);
			}
		});
	}

	// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
	String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
	for (String weaverAwareName : weaverAwareNames) {
		getBean(weaverAwareName);
	}

	// Stop using the temporary ClassLoader for type matching.
	beanFactory.setTempClassLoader(null);

	// Allow for caching all bean definition metadata, not expecting further changes.
	beanFactory.freezeConfiguration();

	// Instantiate all remaining (non-lazy-init) singletons.
	//实例化所有剩下的非懒加载的单实例bean
	beanFactory.preInstantiateSingletons();
}

这个步骤中尤其重要,他的preInstantiateSingletons会实例化所有非懒加载的单实例bean,详见4.实例化所有非懒加载的单实例bean.md

2.2.10. 完成刷新

  • finishRefresh
java 复制代码
protected void finishRefresh() {
	// Initialize lifecycle processor for this context.
	//初始化生命周期有关的PostProcessor
	initLifecycleProcessor();

	// Propagate refresh to lifecycle processor first.
	//调用刚刚的LifecycleProcessor的onRefresh方法
	getLifecycleProcessor().onRefresh();

	// Publish the final event.
	//发布ContextRefreshedEvent事件
	publishEvent(new ContextRefreshedEvent(this));

	// Participate in LiveBeansView MBean, if active.
	LiveBeansView.registerApplicationContext(this);
}
2.2.10.1. 初始化生命周期有关的PostProcessor
  • initLifecycleProcessor
java 复制代码
protected void initLifecycleProcessor() {
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	//获取LifecycleProcessor
	if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
		this.lifecycleProcessor =
				beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
		if (logger.isDebugEnabled()) {
			logger.debug("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
		}
	}
	//没有创建默认的并注册进ioc
	else {
		DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
		defaultProcessor.setBeanFactory(beanFactory);
		this.lifecycleProcessor = defaultProcessor;
		beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
		if (logger.isDebugEnabled()) {
			logger.debug("Unable to locate LifecycleProcessor with name '" +
					LIFECYCLE_PROCESSOR_BEAN_NAME +
					"': using default [" + this.lifecycleProcessor + "]");
		}
	}
}