SpringBoot源码分析
流程图

1.入口
@SpringBootApplication public class SsoApplication{ public static void main(String[] args) { SpringApplication.run(SsoApplication.class, args); } } public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) { return new SpringApplication(primarySources).run(args); }
1.1 new SpringApplication(primarySources);
public SpringApplication(Class<?>... primarySources) { this(null, primarySources); } public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) { this.resourceLoader = resourceLoader; Assert.notNull(primarySources, "PrimarySources must not be null"); this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
// 设置应用程序类型 this.webApplicationType = WebApplicationType.deduceFromClasspath(); // 找出实现ApplicationContextInitializer接口的类 setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class)); // 找出实现ApplicationListener接口的类 setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); this.mainApplicationClass = deduceMainApplicationClass(); } // 从META-INF/spring.factories中获取Spring工厂实例 private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) { ClassLoader classLoader = getClassLoader(); // 使用名称并确保唯一以防止重复 Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader)); // 使用构造方法创建实例 List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names); AnnotationAwareOrderComparator.sort(instances); return instances; } public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) { String factoryTypeName = factoryType.getName(); return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList()); } // 加载META-INF/spring.factories private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) { MultiValueMap<String, String> result = cache.get(classLoader); if (result != null) { return result; } try { Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) : ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION)); result = new LinkedMultiValueMap<>(); while (urls.hasMoreElements()) { URL url = urls.nextElement(); UrlResource resource = new UrlResource(url); Properties properties = PropertiesLoaderUtils.loadProperties(resource); for (Map.Entry<?, ?> entry : properties.entrySet()) { String factoryTypeName = ((String) entry.getKey()).trim(); for (String factoryImplementationName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) { result.add(factoryTypeName, factoryImplementationName.trim()); } } } cache.put(classLoader, result); return result; } ...省略 } // 遍历栈信息,找到调用main方法的类型,将其加载,赋值给变量mainApplicationClass private Class<?> deduceMainApplicationClass() { try { StackTraceElement[] stackTrace = new RuntimeException().getStackTrace(); for (StackTraceElement stackTraceElement : stackTrace) { if ("main".equals(stackTraceElement.getMethodName())) { return Class.forName(stackTraceElement.getClassName()); } } } catch (ClassNotFoundException ex) { // Swallow and continue } return null; }
1.2 run();
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>(); // 设置Headless模式 configureHeadlessProperty();
// 重点① 开启监听,默认的监听器是:EventPublishRunListener 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(); exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[] { ConfigurableApplicationContext.class }, context);
// 重点④ 准备容器 prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// 重点⑤ 刷新容器,注册bean refreshContext(context);
// 空实现方法 afterRefresh(context, applicationArguments); stopWatch.stop(); if (this.logStartupInfo) { new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch); }
// 发布容器启动事件: ApplicationStartedEvent listeners.started(context);
// 执行Runner:ApplicationRunner/CommandLineRunner callRunners(context, applicationArguments); } catch (Throwable ex) { handleRunFailure(context, ex, exceptionReporters, listeners); throw new IllegalStateException(ex); } try {
// 发布容器就绪事件: ApplicationReadyEvent listeners.running(context); } catch (Throwable ex) { handleRunFailure(context, ex, exceptionReporters, null); throw new IllegalStateException(ex); } return context; }
// EventPublishingRunListener 事件广播类
① getRunListenners(args); 开启监听
// 找出实现SpringApplicationRunListener 接口的类 private SpringApplicationRunListeners getRunListeners(String[] args) { Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class }; return new SpringApplicationRunListeners(logger, getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args)); } // 启动监听 SpringApplicationRunListener void starting() { for (SpringApplicationRunListener listener : this.listeners) { listener.starting(); } } // 广播程序开始事件:ApplicationStartingEvent public void starting() { this.initialMulticaster.multicastEvent(new ApplicationStartingEvent(this.application, this.args)); } public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) { ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event)); Executor executor = getTaskExecutor(); // 获取监听当前ApplicationStartingEvent事件的Listener,并遍历执行程序开始事件 for (ApplicationListener<?> listener : getApplicationListeners(event, type)) { if (executor != null) { executor.execute(() -> invokeListener(listener, event)); } else { invokeListener(listener, event); } } }
② prepareEnvironment(listeners, applicationArguments); 准备环境
// 准备环境 private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) { // 创建和配置环境: SERVLET---StandardServletEnvironment ConfigurableEnvironment environment = getOrCreateEnvironment(); // 配置属性资源 configureEnvironment(environment, applicationArguments.getSourceArgs()); // 将配置属性加入环境 ConfigurationPropertySources.attach(environment); // 环境准备 listeners.environmentPrepared(environment); // 将环境绑定到SpringApplication bindToSpringApplication(environment); if (!this.isCustomEnvironment) { environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment, deduceEnvironmentClass()); }
// 将配置属性再次加入环境中 ConfigurationPropertySources.attach(environment); return environment; } // 环境准备 void environmentPrepared(ConfigurableEnvironment environment) { for (SpringApplicationRunListener listener : this.listeners) { listener.environmentPrepared(environment); } } // EventPublishingRunListener下发布环境准备事件: ApplicationEnvironmentPreparedEvent public void environmentPrepared(ConfigurableEnvironment environment) { this.initialMulticaster .multicastEvent(new ApplicationEnvironmentPreparedEvent(this.application, this.args, environment)); } // ConfigFileApplicationListener下监听事件 private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) { List<EnvironmentPostProcessor> postProcessors = loadPostProcessors(); postProcessors.add(this); AnnotationAwareOrderComparator.sort(postProcessors); // 执行后置处理器的环境处理 for (EnvironmentPostProcessor postProcessor : postProcessors) { postProcessor.postProcessEnvironment(event.getEnvironment(), event.getSpringApplication()); } } // 获取环境后置处理器实例 List<EnvironmentPostProcessor> loadPostProcessors() { return SpringFactoriesLoader.loadFactories(EnvironmentPostProcessor.class, getClass().getClassLoader()); } // 将配置文件属性源添加到指定的环境 public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { addPropertySources(environment, application.getResourceLoader()); }
//加载yml或.properties中的配置 protected void addPropertySources(ConfigurableEnvironment environment, ResourceLoader resourceLoader) { RandomValuePropertySource.addToEnvironment(environment); new Loader(environment, resourceLoader).load(); }
③ createApplicationContext(); 创建容器上下文,执行Spring框架中的this();
执行AnnotationConfigServletWebServerApplicationContext() 构造方法;
初始化读取注解的Bean定义读取器,并注册注解配置的的处理器
初始化一个ClassPath类型的Bean的扫描器
// org.springframework.boot.web.servlet.context.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); } } ... } return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass); }
④ prepareContext(...); 准备容器
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) { context.setEnvironment(environment); // 后置处理,注册系统使用Bean postProcessApplicationContext(context); // 执行所有ApplicationContextInitializer实现类初始化 applyInitializers(context); // 发布容器初始化事件:ApplicationContextInitializedEvent listeners.contextPrepared(context); if (this.logStartupInfo) { logStartupInfo(context.getParent() == null); logStartupProfileInfo(context); } // 注册系统单例bean ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); beanFactory.registerSingleton("springApplicationArguments", applicationArguments); if (printedBanner != null) { beanFactory.registerSingleton("springBootBanner", printedBanner); } if (beanFactory instanceof DefaultListableBeanFactory) { ((DefaultListableBeanFactory) beanFactory) .setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding); } //添加延迟初始化BeanFactoryPostProcessor if (this.lazyInitialization) { context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor()); } // 加载资源文件 Set<Object> sources = getAllSources(); Assert.notEmpty(sources, "Sources must not be empty"); // 加载bean 到容器上下文中 load(context, sources.toArray(new Object[0])); // 发布容器准备完成事件: ApplicationPreparedEvent listeners.contextLoaded(context); } // 后置处理 protected void postProcessApplicationContext(ConfigurableApplicationContext context) { if (this.beanNameGenerator != null) { // 注册BeanNameGenerator: org.springframework.context.annotation.internalConfigurationBeanNameGenerator 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()); } } if (this.addConversionService) { context.getBeanFactory().setConversionService(ApplicationConversionService.getSharedInstance()); } } // 执行所有ApplicationContextInitializer实现类初始化 protected void applyInitializers(ConfigurableApplicationContext context) { for (ApplicationContextInitializer initializer : getInitializers()) { Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(), ApplicationContextInitializer.class); Assert.isInstanceOf(requiredType, context, "Unable to call initializer."); initializer.initialize(context); } } // 发布容器初始化事件: ApplicationContextInitializedEvent void contextPrepared(ConfigurableApplicationContext context) { for (SpringApplicationRunListener listener : this.listeners) { listener.contextPrepared(context); } } public void contextPrepared(ConfigurableApplicationContext context) { this.initialMulticaster .multicastEvent(new ApplicationContextInitializedEvent(this.application, this.args, context)); } // 将bean加载到应用程序上下文中 protected void load(ApplicationContext context, Object[] sources) { if (logger.isDebugEnabled()) { logger.debug("Loading source " + StringUtils.arrayToCommaDelimitedString(sources)); } BeanDefinitionLoader loader = createBeanDefinitionLoader(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(); }
⑤ refreshContext(context);刷新容器,注册bean
private void refreshContext(ConfigurableApplicationContext context) { if (this.registerShutdownHook) { try { context.registerShutdownHook(); } ... } refresh((ApplicationContext) context); } protected void refresh(ConfigurableApplicationContext applicationContext) { applicationContext.refresh(); } AbstractApplicationContext下: public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // 准备刷新上下文 prepareRefresh(); // 刷新内部bean工厂 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // 准备BeanFactory prepareBeanFactory(beanFactory); try { // 处理后置处理器,目前没有任何实现 postProcessBeanFactory(beanFactory); /* 拿到所有自定义和内置的BeanDefinitionRegistryPostProcessor后置处理器,循环调用postProcessBeanDefinitionRegistry; 其中最重要的是ConfigurationClassPostProcessor处理器的执行:遍历BeanDefinition找到带有@Configuration注解的BeanDefinition, 解析处理配置类中的@Import,@PropertySources,@ComponentScans(如果存在注解,则会扫描对应路径的类转换成BeanDefinition,
存入BeanDefinitionMap),@Bean(同样)注解等 */ invokeBeanFactoryPostProcessors(beanFactory); // 注册BeanPostProcessor后置处理器 registerBeanPostProcessors(beanFactory); // 初始化消息资源解析器 initMessageSource(); // 初始化注册一个单列ApplicationContext事件监听器applicationEventMulticaster initApplicationEventMulticaster(); // 初始化特定上下文子类中的其他特殊bean。交给子类实现 onRefresh(); //注册事件监听器,派发容器初始化的事件:监听器需要实现ApplicationListener接口 registerListeners(); // 实例所有的单例Bean,创建单例非懒加载的bean finishBeanFactoryInitialization(beanFactory); // 容器初始化完成,发布事件 finishRefresh(); } catch (BeansException ex) { // 销毁已经创建的单实例以避免悬空资源。 destroyBeans(); // 重置 'active' 标记 cancelRefresh(ex); throw ex; } finally { // 重置Spring核心的缓存 resetCommonCaches(); } } }
至此,SpringBoot启动完成。
关于refresh()方法中的源码分析,请参考另一篇: https://www.cnblogs.com/lucky-yqy/p/13854310.html。

浙公网安备 33010602011771号