SpringBoot的启动流程

前言

Spring Boot本身并不提供Spring框架的核心特性以及扩展功能,只是用于快速、敏捷地开发新一代基于Spring框架的应用程序。也就是说,它并不是用来替代Spring的解决方案,而是和Spring框架紧密结合用于提升Spring开发者体验的工具。

项目启动流程

public static void main(String[] args) {
    SpringApplication.run(SpringBootMainApplication.class,args);
}

这是我们最熟悉不过的一句代码,想要知道他的启动流程,这才是入口。我们进入之后.

public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
    return run(new Class[]{primarySource}, args);
}
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
   return (new SpringApplication(primarySources)).run(args);
}

将我们传入的主类包装之后,在进入run方法,这个时候创建一个SpringApplication对象,此时我们就有必要进入他的构造方法了.

public SpringApplication(Class<?>... primarySources) {
        this((ResourceLoader)null, primarySources);
    }

    public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
        this.sources = new LinkedHashSet();
        this.bannerMode = Mode.CONSOLE;
        this.logStartupInfo = true;
        this.addCommandLineProperties = true;
        this.addConversionService = true;
        this.headless = true;
        this.registerShutdownHook = true;
        this.additionalProfiles = new HashSet();
        this.isCustomEnvironment = false;
        this.lazyInitialization = false;
        this.resourceLoader = resourceLoader;
        Assert.notNull(primarySources, "PrimarySources must not be null");
        this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
        this.webApplicationType = WebApplicationType.deduceFromClasspath();
        this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
        this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
        //通过一些堆栈信息递归查找到对应的主启动类
        this.mainApplicationClass = this.deduceMainApplicationClass();
    }

可以看到,他的构造方法其实也并没有做什么事情,就是创建一些实例集合而已,值得注意的是,this.webApplicationType = WebApplicationType.deduceFromClasspath();这句代码是设置servlet环境的,他就是根据我们当前的程序中有没有对应的字节码文件来判断,我们这个时候返回的就是SERVLET。比较重要的是getSpringFactoriesInstances这个方法,这个方法在整个流程中都会使用到。

private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
        ClassLoader classLoader = this.getClassLoader();
        //这里拿到对应type的全类名
        Set<String> names = new LinkedHashSet(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
        List<T> instances = this.createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
        AnnotationAwareOrderComparator.sort(instances);
        return instances;
    }

那其实loadFactoryNames这个方法就是去加载META-INF/spring.factories文件,去找到type对应全类名的所有值.
在这里插入图片描述
这就是spring.factories的部分数据,很明显,我们通过对应type的全类名可以从中找到对应的一些值.知道这个之后,Set names = new LinkedHashSet(SpringFactoriesLoader.loadFactoryNames(type, classLoader));这句代码,就以及得到了type对应的值存放到names这个set集合中.
List instances = this.createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);顾名思义就是去创建对应的实例了,有兴趣的可以进入源码看一下,其实就是反射创建实例 。然后把创建好的实例存放到一个List当中,然后返回这个实例集合。这个时候我们返回到SpringApplication的构造方法中,

this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));

那么这两句代码的作用就显而易见了,就是到spring.factories下面找到ApplicationContextInitializer.class和ApplicationListener.class对应的一些全类名,然后实例化,设置到SpringApplication这个对象当中.此时SpringApplication这个对象就实例化完成了.
接着进入run方法.

public ConfigurableApplicationContext run(String... args) {
		//时间监控
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		ConfigurableApplicationContext context = null;
		Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
		//java.awt.headless是J2SE的一种模式用于在缺少显示屏、键盘或者鼠标时的系统配置,很多监控工具如jconsole 需要将该值设置为true,系统变量默认为true
		configureHeadlessProperty();
		//获取spring.factories中的监听器变量,args为指定的参数数组,默认为当前类SpringApplication
		//第一步:获取并启动监听器
		SpringApplicationRunListeners listeners = getRunListeners(args);
		listeners.starting();
		try {
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(
					args);
			//第二步:构造容器环境
			ConfigurableEnvironment environment = prepareEnvironment(listeners,
					applicationArguments);
			//设置需要忽略的bean
			configureIgnoreBeanInfo(environment);
			//打印banner
			Banner printedBanner = printBanner(environment);
			//第三步:创建容器
			context = createApplicationContext();
			//第四步:实例化SpringBootExceptionReporter.class,用来支持报告关于启动的错误
			exceptionReporters = getSpringFactoriesInstances(
					SpringBootExceptionReporter.class,
					new Class[] { ConfigurableApplicationContext.class }, context);
			//第五步:准备容器
			prepareContext(context, environment, listeners, applicationArguments,
					printedBanner);
			//第六步:刷新容器
			refreshContext(context);
			//第七步:刷新容器后的扩展接口
			afterRefresh(context, applicationArguments);
			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;
	}

第一步:获取并启动监听器
第二步:构造容器环境
第三步:创建容器
第四步:实例化SpringBootExceptionReporter.class,用来支持报告关于启动的错误
第五步:准备容器
第六步:刷新容器
第七步:刷新容器后的扩展接口


一.获取监听器

SpringApplicationRunListeners listeners = this.getRunListeners(args);

private SpringApplicationRunListeners getRunListeners(String[] args) {
        Class<?>[] types = new Class[]{SpringApplication.class, String[].class};
        return new SpringApplicationRunListeners(logger, this.getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args));
    }

上面我们提到getSpringFactoriesInstances这个方法就是获取在spring.factories下type对应的实例类型。SpringApplicationRunListener.class对应的类型是什么呢。

# Run Listeners
org.springframework.boot.SpringApplicationRunListener=\
org.springframework.boot.context.event.EventPublishingRunListener

就是EventPublishingRunListener这个类了。
在这里插入图片描述
debug后我们发现确实是这样。那么,在反射创建EventPublishingRunListener这个对象的时候干了些什么呢。我们去他的构造方法看看。

public EventPublishingRunListener(SpringApplication application, String[] args) {
        this.application = application;
        this.args = args;
        this.initialMulticaster = new SimpleApplicationEventMulticaster();
        Iterator var3 = application.getListeners().iterator();

        while(var3.hasNext()) {
            ApplicationListener<?> listener = (ApplicationListener)var3.next();
            this.initialMulticaster.addApplicationListener(listener);
        }
    }

重点来看一下addApplicationListener方法:

@Override
	public void addApplicationListener(ApplicationListener<?> listener) {
		synchronized (this.retrievalMutex) {
			// Explicitly remove target for a proxy, if registered already,
			// in order to avoid double invocations of the same listener.
			Object singletonTarget = AopProxyUtils.getSingletonTarget(listener);
			if (singletonTarget instanceof ApplicationListener) {
				this.defaultRetriever.applicationListeners.remove(singletonTarget);
			}
			//内部类对象
			this.defaultRetriever.applicationListeners.add(listener);
			this.retrieverCache.clear();
		}
	}

上述方法定义在SimpleApplicationEventMulticaster父类AbstractApplicationEventMulticaster中。关键代码为this.defaultRetriever.applicationListeners.add(listener);,这是一个内部类,用来保存所有的监听器。也就是在这一步,将SpringApplication中在spring.factories中获取的监听器传递到SimpleApplicationEventMulticaster中。

二.启动监听器

listeners.starting();,获取的监听器为EventPublishingRunListener,顾名思义,启动事件发布监听器,主要用来发布启动事件。在这里插入图片描述
这应该很简单,就是获取所有监听器,一个个处理,我们这里的监听器只有这么一个,所以我们直接进入starting方法。

public void starting() {
    this.initialMulticaster.multicastEvent(new ApplicationStartingEvent(this.application, this.args));
}

EventPublishingRunListener这是springBoot框架中最早执行的监听器,在该监听器执行started()方法时,会继续发布事件,也就是事件传递。这种实现主要还是基于spring的事件机制。

public void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType) {
        ResolvableType type = eventType != null ? eventType : this.resolveDefaultEventType(event);
        //获取线程池,如果为空则同步处理。这里线程池为空,还未没初始化。
        Executor executor = this.getTaskExecutor();
        Iterator var5 = this.getApplicationListeners(event, type).iterator();

        while(var5.hasNext()) {
            ApplicationListener<?> listener = (ApplicationListener)var5.next();
            if (executor != null) {
                executor.execute(() -> {
                //异步发送事件
                    this.invokeListener(listener, event);
                });
            } else {
             //同步发送事件
                this.invokeListener(listener, event);
            }
        }
    }

在这里插入图片描述
这里是springboot第一次根据类型执行监听器的地方。根据事件所要发布的事件类型进行事件发布,我们就以第一个日志监听器为例。
在这里插入图片描述

@Override
    public void onApplicationEvent(ApplicationEvent event) {
        //在springboot启动的时候
        if (event instanceof ApplicationStartedEvent) {
            onApplicationStartedEvent((ApplicationStartedEvent) event);
        }
        //springboot的Environment环境准备完成的时候
        else if (event instanceof ApplicationEnvironmentPreparedEvent) {
            onApplicationEnvironmentPreparedEvent(
                    (ApplicationEnvironmentPreparedEvent) event);
        }
        //在springboot容器的环境设置完成以后
        else if (event instanceof ApplicationPreparedEvent) {
            onApplicationPreparedEvent((ApplicationPreparedEvent) event);
        }
        //容器关闭的时候
        else if (event instanceof ContextClosedEvent && ((ContextClosedEvent) event)
                .getApplicationContext().getParent() == null) {
            onContextClosedEvent();
        }
        //容器启动失败的时候
        else if (event instanceof ApplicationFailedEvent) {
            onApplicationFailedEvent();
        }
    }

我们上面执行staring方法的时候,就已经把ApplicationStartingEvent对象作为参数传了进来,所以第一个判断我们就直接可以进去。
在这里插入图片描述
执行完关于日志的操作之后,事件发布完成。springBoot会在运行过程中的不同阶段,发送各种事件,来执行对应监听器的对应方法。我们大致流程就走到这里,以后有需要在叙述。
发布完成之后,一路返回到我们的run方法。

三.环境构建

ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);

private ConfigurableEnvironment prepareEnvironment(
			SpringApplicationRunListeners listeners,
			ApplicationArguments applicationArguments) {
		// Create and configure the environment
		//获取对应的ConfigurableEnvironment
		ConfigurableEnvironment environment = getOrCreateEnvironment();
		//配置
		configureEnvironment(environment, applicationArguments.getSourceArgs());
		//发布环境已准备事件,这是第二次发布事件
		listeners.environmentPrepared(environment);
		bindToSpringApplication(environment);
		if (this.webApplicationType == WebApplicationType.NONE) {
			environment = new EnvironmentConverter(getClassLoader())
					.convertToStandardEnvironmentIfNecessary(environment);
		}
		ConfigurationPropertySources.attach(environment);
		return environment;
	}

首先进来需要拿到我们的环境变量.
在这里插入图片描述
还记得我们上面提到的,我们此时的应用类型是SERVLET类型,所以需要创建StandardServletEnvironment类型的环境。Environment接口提供了4种实现方式,StandardEnvironment、StandardServletEnvironment和MockEnvironment、StandardReactiveWebEnvironment,分别代表普通程序、Web程序、测试程序的环境、响应式web环境,具体后面会详细讲解。这里只需要知道在返回return new StandardServletEnvironment();对象的时候,会完成一系列初始化动作,主要就是将运行机器的系统变量和环境变量,加入到其父类AbstractEnvironment定义的对象MutablePropertySources中,MutablePropertySources对象中定义了一个属性集合:

private final List<PropertySource<?>> propertySourceList = new CopyOnWriteArrayList<PropertySource<?>>();

所以当StandardServletEnvironment环境对象初始化完成,然后执行configureEnvironment方法之后,系统变量和环境变量以及加载到配置文件的集合中。然后,依然是我们的事件机制。具体流程我们上面提过,就不仔细说了。上面我们说他在执行发布事件之前,会根据所发布的事件类型拿到对应的监听器类型,这次我们作为参数传过来的事件类型是ApplicationEnvironmentPreparedEvent类型。
在这里插入图片描述
这次拿到的监听器有这么多,主要来看一下ConfigFileApplicationListener,该监听器非常核心,主要用来处理项目配置。项目中的 properties 和yml文件都是其内部类所加载。

private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) {
        List<EnvironmentPostProcessor> postProcessors = this.loadPostProcessors();
        postProcessors.add(this);
        AnnotationAwareOrderComparator.sort(postProcessors);
        Iterator var3 = postProcessors.iterator();

        while(var3.hasNext()) {
            EnvironmentPostProcessor postProcessor = (EnvironmentPostProcessor)var3.next();
            postProcessor.postProcessEnvironment(event.getEnvironment(), event.getSpringApplication());
        }
    }

在这里插入图片描述
第一步,loadPostProcessors方法,依然是从spring.factories中读取对应的postProcessors。加载完成,然后再把this,也就是ConfigFileApplicationListener添加到postProcessors 这个集合中,也就是说,在下面这个循环中,最后才会去执行ConfigFileApplicationListener的逻辑。而ConfigFileApplicationListener有一个内部类,Loader,它负责加载配置路径下的配置文件。而默认配置文件路径在这个类中也有所定义。

    private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/";

那么在事件执行ConfigFileApplicationListener的事件发布的时候,他就会去读取配置路径下的配置文件。在这里插入图片描述
最后一个就是我们自己定义的配置文件了。至此,环境配置完成。

四.容器构建

context = this.createApplicationContext();

protected ConfigurableApplicationContext createApplicationContext() {
        Class<?> contextClass = this.applicationContextClass;
        if (contextClass == null) {
            try {
                switch(this.webApplicationType) {
                case SERVLET:
                    contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext");
                    break;
                case REACTIVE:
                    contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext");
                    break;
                default:
                    contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext");
                }
            } catch (ClassNotFoundException var3) {
                throw new IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3);
            }
        }

        return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass);
    }

很明显,这里是通过webApplicationType来判断所创建的容器类型,那么此时我们所装载的字节码是org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext
装载好字节码之后,后续就会使用BeanUtils来进行实例化了。这里要提一下,在实例化这个类的时候,同时也会去实例化他的父类,那么在他的父类GenericApplicationContext的构造方法中,创建了一个beanFactrory。在这里插入图片描述
类型依然是我们比较熟悉的DefaultListableBeanFactory类型。

五.错误报告

exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);

还是以同样的方式去spring.factories下面获取指定类,该类主要是在项目启动失败之后,打印log

六.准备容器

 this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
private void prepareContext(ConfigurableApplicationContext context,
			ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
			ApplicationArguments applicationArguments, Banner printedBanner) {
		//设置容器环境,包括各种变量
		context.setEnvironment(environment);
		//执行容器后置处理
		postProcessApplicationContext(context);
		//执行容器中的ApplicationContextInitializer(包括 spring.factories和自定义的实例)
		applyInitializers(context);
		//发送容器已经准备好的事件,通知各监听器
		listeners.contextPrepared(context);
		//打印log
		if (this.logStartupInfo) {
			logStartupInfo(context.getParent() == null);
			logStartupProfileInfo(context);
		}
		// Add boot specific singleton beans
		//注册启动参数bean,这里将容器指定的参数封装成bean,注入容器
		context.getBeanFactory().registerSingleton("springApplicationArguments",
				applicationArguments);
		//设置banner
		if (printedBanner != null) {
			context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
		}
		// Load the sources
		//获取我们的启动类指定的参数,可以是多个
		Set<Object> sources = getAllSources();
		Assert.notEmpty(sources, "Sources must not be empty");
		//加载我们的启动类,将启动类注入容器
		load(context, sources.toArray(new Object[0]));
		//发布容器已加载事件。
		listeners.contextLoaded(context);
	}

容器的后置处理

	protected void postProcessApplicationContext(ConfigurableApplicationContext context) {
		if (this.beanNameGenerator != null) {
			context.getBeanFactory().registerSingleton(
					AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR,
					this.beanNameGenerator);
		}
		if (this.resourceLoader != null) {
			if (context instanceof GenericApplicationContext) {
				((GenericApplicationContext) context)
						.setResourceLoader(this.resourceLoader);
			}
			if (context instanceof DefaultResourceLoader) {
				((DefaultResourceLoader) context)
						.setClassLoader(this.resourceLoader.getClassLoader());
			}
		}
	}

这里其实是不执行任何逻辑的,因为此时的beanNameGenerator 和resourceLoader 都默认为null。这里其实是留给我们扩展的处理方式。后置处理之后,拿到我们上面在容器初始化时候所创建的beanFactory实例,然后注册一些Bean,设置一些属性之后,就会去加载启动类。

加载启动类

this.load(context, sources.toArray(new Object[0]));
protected void load(ApplicationContext context, Object[] sources) {
        if (logger.isDebugEnabled()) {
            logger.debug("Loading source " + StringUtils.arrayToCommaDelimitedString(sources));
        }

        BeanDefinitionLoader loader = this.createBeanDefinitionLoader(this.getBeanDefinitionRegistry(context), sources);
        if (this.beanNameGenerator != null) {
            loader.setBeanNameGenerator(this.beanNameGenerator);
        }

        if (this.resourceLoader != null) {
            loader.setResourceLoader(this.resourceLoader);
        }

        if (this.environment != null) {
            loader.setEnvironment(this.environment);
        }
        loader.load();
    }

这里参数即为我们项目启动时传递的参数:SpringApplication.run(SpringBootMainApplication.class, args);由于我们指定了启动类,所以上面也就是加载启动类到容器。

	private int load(Class<?> source) {
		if (isGroovyPresent()
				&& GroovyBeanDefinitionSource.class.isAssignableFrom(source)) {
			// Any GroovyLoaders added in beans{} DSL can contribute beans here
			GroovyBeanDefinitionSource loader = BeanUtils.instantiateClass(source,
					GroovyBeanDefinitionSource.class);
			load(loader);
		}
		if (isComponent(source)) {
			//以注解的方式,将启动类bean信息存入beanDefinitionMap
			this.annotatedReader.register(source);
			return 1;
		}
		return 0;
	}

加载完成之后,通过监听器对日志做一些处理。容器准备完成。

七.刷新容器

synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			/**
			 * 刷新上下文环境
			 * 初始化上下文环境,对系统的环境变量或者系统属性进行准备和校验
			 * 如环境变量中必须设置某个值才能运行,否则不能运行,这个时候可以在这里加这个校验,
			 * 重写initPropertySources方法就好了
			 */
			prepareRefresh();
 
			// Tell the subclass to refresh the internal bean factory.
			/**
			 * 初始化BeanFactory,解析XML,相当于之前的XmlBeanFactory的操作,
			 */
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
 
			// Prepare the bean factory for use in this context.
			/**
			 * 为上下文准备BeanFactory,即对BeanFactory的各种功能进行填充,如常用的注解@Autowired @Qualifier等
			 * 设置SPEL表达式#{key}的解析器
			 * 设置资源编辑注册器,如PerpertyEditorSupper的支持
			 * 添加ApplicationContextAwareProcessor处理器
			 * 在依赖注入忽略实现*Aware的接口,如EnvironmentAware、ApplicationEventPublisherAware等
			 * 注册依赖,如一个bean的属性中含有ApplicationEventPublisher(beanFactory),则会将beanFactory的实例注入进去
			 */
			prepareBeanFactory(beanFactory);
 
			try {
				// Allows post-processing of the bean factory in context subclasses.
				/**
				 * 提供子类覆盖的额外处理,即子类处理自定义的BeanFactoryPostProcess
				 */
				postProcessBeanFactory(beanFactory);
 
				// Invoke factory processors registered as beans in the context.
				/**
				 * 激活各种BeanFactory处理器,包括BeanDefinitionRegistryBeanFactoryPostProcessor和普通的BeanFactoryPostProcessor
				 * 执行对应的postProcessBeanDefinitionRegistry方法 和  postProcessBeanFactory方法
				 */
				invokeBeanFactoryPostProcessors(beanFactory);
 
				// Register bean processors that intercept bean creation.
				/**
				 * 注册拦截Bean创建的Bean处理器,即注册BeanPostProcessor,不是BeanFactoryPostProcessor,注意两者的区别
				 * 注意,这里仅仅是注册,并不会执行对应的方法,将在bean的实例化时执行对应的方法
				 */
				registerBeanPostProcessors(beanFactory);
 
				// Initialize message source for this context.
				/**
				 * 初始化上下文中的资源文件,如国际化文件的处理等
				 */
				initMessageSource();
 
				// Initialize event multicaster for this context.
				/**
				 * 初始化上下文事件广播器,并放入applicatioEventMulticaster,如ApplicationEventPublisher
				 */
				initApplicationEventMulticaster();
 
				// Initialize other special beans in specific context subclasses.
				/**
				 * 给子类扩展初始化其他Bean
				 */
				onRefresh();
 
				// Check for listener beans and register them.
				/**
				 * 在所有bean中查找listener bean,然后注册到广播器中
				 */
				registerListeners();
 
				// Instantiate all remaining (non-lazy-init) singletons.
				/**
				 * 设置转换器
				 * 注册一个默认的属性值解析器
				 * 冻结所有的bean定义,说明注册的bean定义将不能被修改或进一步的处理
				 * 初始化剩余的非惰性的bean,即初始化非延迟加载的bean
				 */
				finishBeanFactoryInitialization(beanFactory);
 
				// Last step: publish corresponding event.
				/**
				 * 初始化生命周期处理器DefaultLifecycleProcessor,DefaultLifecycleProcessor含有start方法和stop方法,spring启动的时候调用start方法开始生命周期,
				 * spring关闭的时候调用stop方法来结束生命周期,通常用来配置后台程序,启动有一直运行,如一直轮询kafka
				 * 启动所有实现了Lifecycle接口的类
				 * 通过spring的事件发布机制发布ContextRefreshedEvent事件,以保证对应的监听器做进一步的处理,即对那种在spring启动后需要处理的一些类,这些类实现了
				 * ApplicationListener<ContextRefreshedEvent> ,这里就是要触发这些类的执行(执行onApplicationEvent方法)另外,spring的内置Event有ContextClosedEvent、ContextRefreshedEvent、ContextStartedEvent、ContextStoppedEvent、RequestHandleEvent
				 * 完成初始化,通知生命周期处理器lifeCycleProcessor刷新过程,同时发出ContextRefreshEvent通知其他人
				 */
				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();
			}
		}

refresh方法是spring当中的核心方法,是实现 ioc 和 aop的关键,这个方法结束之后,回到我们的run方法当中。

八.刷新容器后的扩展接口

protected void afterRefresh(ConfigurableApplicationContext context,
			ApplicationArguments args) {
	}

扩展接口,设计模式中的模板方法,默认为空实现。如果有自定义需求,可以重写该方法。比如打印一些启动结束log,或者一些其它后置处理。


springBoot2启动流程到这里就结束了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值