springboot 源码理解

最近在看springboot 启动流程,以下就是我自己对springboot启动时执行流程的一些理解。我使用的springboot版本为 2.2.11.

开始源码阅读

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {

		SpringApplication.run(DemoApplication.class,args);
	}
}
    /**
	 * Static helper that can be used to run a {@link SpringApplication} from the
	 * specified sources using default settings and user supplied arguments.
	 * @param primarySources the primary sources to load
	 * @param args the application arguments (usually passed from a Java main method)
	 * @return the running {@link ApplicationContext}
	 */
	public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
		return new SpringApplication(primarySources).run(args);
	}

由此可以看出springboot 在启动的过程主要是通过两个部分来进行完成的。1,构造器初始化 2.run方法执行的逻辑。

首先看下构造器里面实现的逻辑,我先上一张图,主要的执行如下图所示。

 

public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
		
        // 默认为null
        this.resourceLoader = resourceLoader;
		Assert.notNull(primarySources, "PrimarySources must not be null");
        // 1. 初始化主的资源
		this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
        // 2. 推断应用类型 
		this.webApplicationType = WebApplicationType.deduceFromClasspath();
        // 3. 初始化所有实现 ApplicationContextInitializer的子类
		setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
        // 4. 初始化所有的实现ApplicationListener 的监听器,过程和3中的逻辑是一样的
		setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
        // 5. 获取mian方法  (这块的思路比较好,以下会有介绍)
		this.mainApplicationClass = deduceMainApplicationClass();
	}

 2.推断应用类型,这个就是根据类是否加载来判断应用的类型,我引用的包为spring-boot-starter-web 因此为SERVLET类型,感兴趣的可以看下这块源码。

 3. 初始化所有实现ApplicationContextInitializer类型应用上下文

private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
		return getSpringFactoriesInstances(type, new Class<?>[] {});
	}

private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
        // 获取类加载器
		ClassLoader classLoader = getClassLoader();
		// Use names and ensure unique to protect against duplicates
        // 获取工程名称
		Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
        // 创建bena工厂实例
		List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
        // 排序
		AnnotationAwareOrderComparator.sort(instances);
		return instances;
	}

其中SpringFactoriesLoader.loadFactoryNames(type, classLoader) 这个方式是重点,意思就是在classpath 路径下获取接口的实现类名称,获取之后将其放入到缓存中,方便后续的处理

public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
		String factoryTypeName = factoryType.getName();
		return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
	}

	private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
		MultiValueMap<String, String> result = cache.get(classLoader);
		if (result != null) {
			return result;
		}

		try {
        // FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
        // 获取加载路径
			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;
		}
		catch (IOException ex) {
			throw new IllegalArgumentException("Unable to load factories from location [" +
					FACTORIES_RESOURCE_LOCATION + "]", ex);
		}
	}

4. 中获取监听器的方法和3中的是相同的套路。

5. 中获取main方法的思路比较好,是直接new出一个运行期的异常通过堆栈信息来获取main方法,这个思路比较好。

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

到此springboot实例化中做的初始化工作已经完成了,接下来就是run方法中的逻辑了。

public ConfigurableApplicationContext run(String... args) {
        // 计时器,相当于System.currentTimeMillis()获取时间进行相减来获取方法的耗时时间
		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);
            // 设置忽略的bean信息
			configureIgnoreBeanInfo(environment);
            // 打印banner,
			Banner printedBanner = printBanner(environment);
            // 创建IOC容器
			context = createApplicationContext();
            // 加载异常的类型信息,和构造方法中的是相同的套路
			exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
					new Class[] { ConfigurableApplicationContext.class }, context);
            // IOC容器前置处理
			prepareContext(context, environment, listeners, applicationArguments, printedBanner);
            // 刷新容器
			refreshContext(context);
            // IOC容器后置处理
			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;
	}

总结了下run方法的主要执行流程

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值