SpringBoot 初始化过程的核心类ApplicationContext解析

SpringBoot 初始化过程

SpringBoot初始化所用到的ApplicationContextAnnotationConfigServletWebServerApplicationContext

1.AnnotationConfigServletWebServerApplicationContext的继承关系

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Wsk5CeQ5-1595380972906)(DB05F5E1F81D421E85756384C83993CF)]AnnotationConfigServletwebServerApplicationContext结构图
  从上面的继承图看AnnotationConfigServletwebServerApplicationContext的结构是非常错杂凌乱的,现在我们分开来看。首先进入AnnotationConfigServletwebServerApplicationContext类里面,看看他的内部结构是什么,发现有两个重要构造器,一个构造器是默认构造器,初始化了AnnotatedBeanDefinitionReaderClassPathBeanDefinationScanner类作为AnnotationConfigServletwebServerApplicationContext的两个属性,如下代码所示,另一是有参构造器,传递的参数是DefaultListableBeanFactory

//无参构造器初始化的时候,只创建了AnnotatedBeanDefinitionReader和ClassPathBeanDefinitionScanner两个类
public AnnotationConfigServletWebServerApplicationContext() {
		this.reader = new AnnotatedBeanDefinitionReader(this);
		this.scanner = new ClassPathBeanDefinitionScanner(this);
	}
//有参构造器,参数是DefaultListableBeanFactory
public AnnotationConfigServletWebServerApplicationContext(
			DefaultListableBeanFactory beanFactory) {
		super(beanFactory);
		this.reader = new AnnotatedBeanDefinitionReader(this);
		this.scanner = new ClassPathBeanDefinitionScanner(this);
	}

  那么DefaultListBeanFactory是个什么样的类呢?从它的结构来看,是个BeanFactory,注释说明:这个类是ConfigurableListableBeanFactory的实现类(此类研究先告一段落,后面使用到了再详解)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yMSsB5AL-1595380972914)(A90E50AD902D4AECA820BCBA0297B509)]
DefaultListableBeanFactory 结构图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ea6o0Gqd-1595380972918)(753F8B50028D4C28BFD3C7E74D87B98C)]
ConfigurableListableBeanFactory结构图

 下面我们继续来看springBoot的初始化过程,当springBoot从添加注解@SpringBootApplication的main方法开始执行run的时候,就进入了下面的静态代码。这里注意,返回的是ConfigurableApplicationContext接口,这个接口的实现,就是我们上面提到的SpringBoot的最核心的类的接口实现类AnnotationConfigServletwebServerApplicationContext,也就是说,SpringBoot启动的过程,就是创建ConfigurableApplicationContext实现类的过程。

//SpringApplication的run()方法:
	public static ConfigurableApplicationContext run(Class<?> primarySource,
   		String... args) {
   	return run(new Class<?>[] { primarySource }, args);
   }

  从ConfigurableApplicationContext的结构图我们可以看到,里面最核心的接口是ApplicationContext,既IOC容器的接口类,它是Spring非常非常重要的接口,整个Spring就围绕着这个接口打转转了。我们下面继续看到底是怎么初始化的,怎么获取到ConfigurableApplicationContext的。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JeRgT7a1-1595380972922)(F23283E9D9D24A3F89C65FFBF6F8F329)]
ConfigurableApplicationContext结构图

 继续看SpringApplication的run方法,里面做了什么操作,通过下面的代码逻辑,我们将run()方法大体经典分为5大步骤,1.创建ConfigurableApplicationContext实现,2.准备环境,3.刷新容器,4.刷新容器后所做的事情,下面看这五大步骤的执行过程。

public ConfigurableApplicationContext run(String... args) {
   	StopWatch stopWatch = new StopWatch();
   	stopWatch.start();
   	ConfigurableApplicationContext context = null;//这里是创建过程,下面查看怎么创建
   	Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
   	configureHeadlessProperty();
   	SpringApplicationRunListeners listeners = getRunListeners(args);
   	listeners.starting();
   	try {
   		ApplicationArguments applicationArguments = new DefaultApplicationArguments(
   				args);
   		ConfigurableEnvironment environment = prepareEnvironment(listeners,
   				applicationArguments);
   		configureIgnoreBeanInfo(environment);
   		Banner printedBanner = printBanner(environment);
   		context = createApplicationContext();//1.创建ConfigurableApplicationContext实现
   		exceptionReporters = getSpringFactoriesInstances(
   				SpringBootExceptionReporter.class,
   				new Class[] { ConfigurableApplicationContext.class }, context);
   		prepareContext(context, environment, listeners, applicationArguments,
   				printedBanner);//2.准备环境
   		refreshContext(context);//3.刷新容器
   		afterRefresh(context, applicationArguments);//4.刷新容器后所做的事情
   		stopWatch.stop();
   		if (this.logStartupInfo) {
   			new StartupInfoLogger(this.mainApplicationClass)
   					.logStarted(getApplicationLog(), stopWatch);
   		}
   		listeners.started(context);
   		callRunners(context, applicationArguments);
   	}
   	catch (Throwable ex) {
   		handleRunFailure(context, ex, exceptionReporters, listeners);
   		throw new IllegalStateException(ex);
   	}

   	try {
   		listeners.running(context);
   	}
   	catch (Throwable ex) {
   		handleRunFailure(context, ex, exceptionReporters, null);
   		throw new IllegalStateException(ex);
   	}
   	return context;
   }
1.创建ConfigurableApplicationContext实现

   查看内嵌的web容器是什么:Tomcat(Servlet),Netty(reactive)。这里是Servlet,所以实例化DEFAULT_SERVLET_WEB_CONTEXT_CLASS= "org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext";,可以看出,这里正是创建了ConfigurableApplicationContext的实现类:AnnotationConfigServletWebServerApplicationContext

protected ConfigurableApplicationContext createApplicationContext() {
		Class<?> contextClass = this.applicationContextClass;
		if (contextClass == null) {
			try {
				switch (this.webApplicationType) {
				case SERVLET:
					contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
					break;
				case REACTIVE:
					contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
					break;
				default:
					contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
				}
			}
			catch (ClassNotFoundException ex) {
				throw new IllegalStateException(
						"Unable create a default ApplicationContext, "
								+ "please specify an ApplicationContextClass",
						ex);
			}
		}
		return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
	}
2.准备环境

  SpringBoot在run()方法初始化环境准备的过程,就是实例化ConfigurableEnvironment的过程,那么ConfigurableEnvironment是个什么类呢?为什么要对它进行启动,他有什么特别之处。下面下看看它的类结构图。它的主要作用是做环境Environment的准备。实现类在SpringBoot中有下面方法来决定:可以看到,实现类是StandardServletEnvironment,对它的详细描述,后面在做详解。

	private ConfigurableEnvironment getOrCreateEnvironment() {
		if (this.environment != null) {
			return this.environment;
		}
		switch (this.webApplicationType) {
		case SERVLET:
			return new StandardServletEnvironment();
		case REACTIVE:
			return new StandardReactiveWebEnvironment();
		default:
			return new StandardEnvironment();
		}
	}

在这里插入图片描述
ConfigurationEnvironment结构图
StandardServletEnvironment结构图

3.刷新容器

  这一步是Spring最核心的部分,主要做了将所有Bean加载到IOC容器的过程,代码如下:

	prepareContext(context, environment, listeners, applicationArguments,printedBanner);
    refreshContext(context);
    afterRefresh(context, applicationArguments);

最最核心的就是refreshContext(context),整个IOC容器加载Bean的过程全部在这个里面完成,如下代码:

public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// 准备刷新容器(这里清除缓存,并读取配置文件里的环境变量)
			prepareRefresh();

			// 告诉子类刷新内部Bean 工厂类
			//此处的 bean factory 是通过父类GenericApplicationContext 初始化的 DefaultListableBeanFactory
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				//ResourceLoader、ApplicationEventPublisher、ApplicationContext这3个接口对应的bean都设置为当前的Spring容器,注册环境bean
				postProcessBeanFactory(beanFactory);

	     // 实例化beanFactoryPostProcessor
         // 调用beanFactoryPostProcessor 这里会调用ConfigurationClassPostProcessor,解析@Configuration的类为BeanDefinition,为后面实例化作准备
				invokeBeanFactoryPostProcessors(beanFactory);

		 // 注册 beanPostProcessors 包括自定义的BeanPostProcessor
		 // 在实例化Bean后处理 比如AutowiredAnnotationBeanPostProcessor(处理被@Autowired注解修饰的bean并注入)、RequiredAnnotationBeanPostProcessor(处理被@Required注解修饰的方法)
		 // 这些都是在创建Context时的reader的构造器中的AnnotationConfigUtils的registerAnnotationConfigProcessors方法中注册的
				registerBeanPostProcessors(beanFactory);

				// 初始化信息源,和国际化相关
				initMessageSource();

				// // 初始化容器事件传播器
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				// 调用子类特殊的刷新逻辑
		 // web程序的容器AnnotationConfigEmbeddedWebApplicationContext中会调用createEmbeddedServletContainer方法去创建内置的Servlet容器。
				onRefresh();

				// 为事件传播器注册事件监听器.
				registerListeners();

				// 实例化所有非懒加载单例
				finishBeanFactoryInitialization(beanFactory);

				//初始化容器的生命周期事件处理器,并发布容器的生命周期事件
				finishRefresh();
			}

			catch (BeansException ex) {
			//...

			finally {
		
				resetCommonCaches();
			}
		}
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值