SpringIOC容器初始化流程12大步源码解析

目录

1.概要及容器初始化流程图

2.AnnotationConfigApplicationContext构造器

3.第一步--prepareRefresh()准备上下文环境

4.第二步--创建工厂实例

5.第三步--预准备工厂

6.第四步--postProcessBeanFactory

7.第五步--执行所有的BeanFactory后置增强器

8.第六步--注册所有的bean的后置处理器 BeanPostProcessors

9.第七步--初始化国际化组件

10.第八步--初始化事件多播器组件

11.第九步--onRefresh

12.第十步--注册早期的监听器

13.第十一步--大大核心完成BeanFactory初始化, 创建所有组件

14. 第十二步--收尾工作finishRefresh


1.概要及IOC容器初始化流程图

下面是IOC初始化的完整流程图

 

就以我们new了一个AnnotationConfigApplicationContext 为例,参数穿传的是我们的是我们的主配置类, 配置类就简单加俩注解@Configuration、@ComponentScan("com.xixi")  ,new 一个AnnotationConfigApplicationContext 就是创建了一个IOC容器,里面就进行了12个步骤来初始化容器


//伪代码 简单写下
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);

@ComponentScan("com")
@Configuration
public class MainConfig {

}

以下是Spring刷新容器的代码,Spring中起了个名叫刷新,其实就是创建IOC容器,一共就12步 debug逐个击破就完了 非常的easy

	@Override  //容器刷新的十二大步。模板模式
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

			//1.准备上下文环境 Prepare this context for refreshing.
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			// 2.工厂创建:BeanFactory第一次开始创建的时候,有xml解析逻辑。
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			//3.给容器中注册了环境信息作为单实例Bean方便后续自动装配;放了一些后置处理器处理(监听、xxAware功能) Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				//4.留给子类的模板方法,允许子类继续对工厂执行一些处理; Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
				//5.【大核心】工厂增强:执行所有的BeanFactory后置增强器;利用BeanFactory后置增强器对工厂进行修改或者增强,配置类会在这里进行解析。 Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

				//6.【核心】注册所有的Bean的后置处理器 Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);
				beanPostProcess.end();

				//7.初始化国际化功能 Initialize message source for this context.
				initMessageSource();

				//8.初始化事件多播功能(事件派发) Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				//9. Initialize other special beans in specific context subclasses.
				onRefresh();

				//10.注册监听器,从容器中获取所有的ApplicationListener; Check for listener beans and register them.
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				//11.【大核心】bean创建;完成 BeanFactory 初始化。(工厂里面所有的组件都好了)
				finishBeanFactoryInitialization(beanFactory);

				//12.发布事件 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 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();
				contextRefresh.end();
			}
		}
	}

 

2.AnnotationConfigApplicationContext构造器

分析12大步之前先看下this()里边干了啥

public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
		this();
		register(componentClasses);
		refresh(); //容器完整刷新(创建出所有组件,组织好所有功能)
	}

 下面是this中的代码,可以看到主要就创建了俩基础组件  AnnotatedBeanDefinitionReader Bean定义的读取器,ClassPathBeanDefinitionScanner bean定义的扫描器,用来扫描指定路径下所有的bean信息

public AnnotationConfigApplicationContext() {
		StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");
		this.reader = new AnnotatedBeanDefinitionReader(this);
		createAnnotatedBeanDefReader.end();
		this.scanner = new ClassPathBeanDefinitionScanner(this);
	}

重点看下创建读取器过程,里面调用了registerAnnotationConfigProcessors方法给工厂创建了很多基础组件,各种解析器

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

可以看到里面注册了ConfigurationClassPostProcessor 配置类的后置处理器,我们加了@Configuration注解的类就是用这个处理器来解析的,还有AutowiredAnnotationBeanPostProcessor自动化装配相关的后置处理器等等

	public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
			BeanDefinitionRegistry registry, @Nullable Object source) {

		DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
		if (beanFactory != null) {
			if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
				beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
			}
			if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
				beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
			}
		}

		Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
		//注册底层的  配置文件处理器
		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));
		}
        //注册底层的自动装配处理器
		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));
		}
        //注册支持JSR-250的处理
		// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
		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));
		}

		// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
		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));
		}

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

		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;
	}

this()里边就是定义一些Spring容器底层用到的一些基础组件。

然后看下一步register(componentClasses);方法,compo

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值