Spring启动流程
随着springboot的功能越来越强大,我们逐渐忘记了spring,但是每当遇到问题时缺无从下手,
我们在享受springboot给我们带来的便利的同时更应该了解其底层原理,知其然更要知其所以然,下面我们一起进入spring的世界探索吧
Spring启动
我们从springboot的入口(不使用springboot的方式放在后面文章讲解)来看spring是如何被启动的
我们都有启动类如下
AttachCode
@SpringBootApplication
public class Main {public static void main(String[] args) {SpringApplication.run(Main.class, args);}
我们先来看下SpringApplication.run(Main.class, args);
我们今天的主要内容不是springboot,所以我们一路跟踪到spring的refesh方法
AttachCode
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {return (new SpringApplication(primarySources)).run(args);}
AttachCode
public void refresh(){
//省略部分代码
this.refreshContext(context);
//省略部分代码
}
AttachCode
private void refreshContext(ConfigurableApplicationContext context) {if (this.registerShutdownHook) {shutdownHook.registerApplicationContext(context);}this.refresh(context);}
今天的主角AttachCode
@Overridepublic void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");// Prepare this context for refreshing.prepareRefresh();// Tell the subclass to refresh the internal bean factory.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.postProcessBeanFactory(beanFactory);StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");// Invoke factory processors registered as beans in the context.invokeBeanFactoryPostProcessors(beanFactory);// Register bean processors that intercept bean creation.registerBeanPostProcessors(beanFactory);beanPostProcess.end();// 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.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 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();}}}
今天我们先到这里
本文由 idea的插件"AnNote"协助完成,是一款源码学习笔记,不但能够帮助我们做笔记、分享笔记还可以学习学霸的笔记。欢迎大家试用
本文由博客群发一文多发等运营工具平台 OpenWrite 发布