Spring Boot 源码分析

本文深入探讨Spring Boot的初始化过程,包括SpringApplication的构造与run方法。详细解析了SpringFactoriesLoader如何加载Initializers和Listeners,并介绍了run方法中的事件监听流程,如ApplicationStartedEvent、ApplicationEnvironmentPreparedEvent等。此外,还分析了SpringApplicationRunListeners在事件广播中的作用。
摘要由CSDN通过智能技术生成

1、项目初始化过程

SpringBoot的启动很简单,代码如下:

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

跟进去可以看到有两步,一个是初始化,一个是run方法的执行:

1.SpringApplication初始化化过程:

SpringApplication的初始化大致分为以下的步骤:

  1. 判断是否是web应用程序
  2. 从所有类中查找META-INF/spring.factories文件,加载其中的初始化类和监听类。
  3. 查找运行的主类 默认初始化Initializers都继承自ApplicationContextInitializer。

SpringApplication构建函数:

public SpringApplication(ResourceLoader resourceLoader, Object... sources) {
	this.resourceLoader = resourceLoader;
	initialize(sources);
}
         private void initialize(Object[] sources) {
		if (sources != null && sources.length > 0) {
			this.sources.addAll(Arrays.asList(sources));
		}
		//是否是web应用程序。通过判断应用程序中是否可以加载(class.forname)【"javax.servlet.Servlet","org.springframework.web.context.ConfigurableWebApplicationContext"】这两个类
		this.webEnvironment = deduceWebEnvironment();
		//设置初始化类:从配置文件spring.factories中查找所有的key=org.springframework.context.ApplicationContextInitializer的类【加载,初始化,排序】
        //SpringFactoriesLoader:工厂加载机制
		setInitializers((Collection) getSpringFactoriesInstances(
				ApplicationContextInitializer.class));
	    //设置Listeners:从配置文件spring.factories中查找所有的key=org.springframework.context.ApplicationListener的类.【加载,初始化,排序】
		setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
		 //从当前调用栈中,查找主类
		this.mainApplicationClass = deduceMainApplicationClass();
	}
2.SpringFactoriesLoader工厂加载机制

Initializers和Listeners的加载过程都是使用到了SpringFactoriesLoader工厂加载机制。我们进入到getSpringFactoriesInstances这个方法中:

      private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type,
		Class<?>[] parameterTypes, Object... args) {
	ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
	// Use names and ensure unique to protect against duplicates
	//获取META-INF/spring.factories文件中key为type类型的所有的类全限定名。注意是所有jar包内的。
	Set<String> names = new LinkedHashSet<String>(
			SpringFactoriesLoader.loadFactoryNames(type, classLoader));
			
       //通过上面获取到的类的全限定名,这里将会使用Class.forName加载类,并调用构造方法实例化类
	List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
			classLoader, args, names);

         //根据类上的org.springframework.core.annotation.Order注解,排序
	AnnotationAwareOrderComparator.sort(instances);
	return instances;
}

SpringFactoriesLoader.loadFactoryNames(type, classLoader));展示类方法加载的过程:

public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
	String factoryClassName = factoryClass.getName();
	try {
		Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
				ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
		List<String> result = new ArrayList<String>();
		while (urls.hasMoreElements()) {
			URL url = urls.nextElement();
			Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
			String factoryClassNames = properties.getProperty(factoryClassName);
			result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
		}
		return result;
	}
	catch (IOException ex) {
		throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() +
				"] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
	}
}

ApplicationContextInitializer的类图:
在这里插入图片描述

初始化ApplicationContextInitializer:
“org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer”
“org.springframework.boot.context.ContextIdApplicationContextInitializer”
“org.springframework.boot.context.config.DelegatingApplicationContextInitializer”
“org.springframework.boot.context.web.ServerPortInfoApplicationContextInitializer”
“org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer”
“org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer”

初始化ApplicationListener:
“org.springframework.boot.ClearCachesApplicationListener”
“org.springframework.boot.builder.ParentContextCloserApplicationListener”
“org.springframework.boot.context.FileEncodingApplicationListener”
“org.springframework.boot.context.config.AnsiOutputApplicationListener”
“org.springframework.boot.context.config.ConfigFileApplicationListener”
“org.springframework.boot.context.config.DelegatingApplicationListener”
“org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener”
“org.springframework.boot.logging.ClasspathLoggingApplicationListener”
“org.springframework.boot.logging.LoggingApplicationListener”
“org.springframework.boot.autoconfigure.BackgroundPreinitializer”

3.Run 方法

启动run过程

  1. 注册一个StopWatch,用于监控启动过程
  2. 获取监听器SpringApplicationRunListener,用于springboot启动过程中的事件广播
  3. 设置环境变量environment
  4. 创建spring容器
  5. 创建FailureAnalyzers错误分析器,用于处理记录启动过程中的错误信息
  6. 调用所有初始化类的initialize方法
  7. 初始化spring容器
  8. 执行ApplicationRunner和CommandLineRunner的实现类
  9. 启动完成
public ConfigurableApplicationContext run(String... args) {	
             //stopWatch 用于简单监听run启动过程
	StopWatch stopWatch = new StopWatch();
	stopWatch.start();
	ConfigurableApplicationContext context = null;
	FailureAnalyzers analyzers = null;
	configureHeadlessProperty();
	 //获取监听器。springboot中有一个SpringApplicationRunListener监听器
	SpringApplicationRunListeners listeners = getRunListeners(args);
	listeners.started();
	try {
	  //下面两句是加载属性配置,执行完成后,所有的environment的属性都会加载进来,包括application.properties和外部的属性配置。
		ApplicationArguments applicationArguments = new DefaultApplicationArguments(
				args);
		ConfigurableEnvironment environment = prepareEnvironment(listeners,
				applicationArguments);
		//打印Banner		
		Banner printedBanner = printBanner(environment);
		context = createApplicationContext();
		//错误分析器
		analyzers = new FailureAnalyzers(context);
            //主要是调用所有初始化类的initialize方法
		prepareContext(context, environment, listeners, applicationArguments,
				printedBanner);
		//初始化spring容器
		refreshContext(context);
		//主要是执行ApplicationRunner和CommandLineRunner的实现类
		afterRefresh(context, applicationArguments);
		//通知监听器
		listeners.finished(context, null);
		stopWatch.stop();
		if (this.logStartupInfo) {
			new StartupInfoLogger(this.mainApplicationClass)
					.logStarted(getApplicationLog(), stopWatch);
		}
		return context;
	}
	catch (Throwable ex) {
		handleRunFailure(context, listeners, analyzers, ex);
		throw new IllegalStateException(ex);
	}
}

上述run过程广泛应用了spring事件机制(主要是广播)。上述代码中首先获取SpringApplicationRunListeners。这就是在spring.factories文件中配置的所有监听器。然后整个run 过程使用了listeners的5个方法,每个方法对应一个事件Event:

starting() run方法执行的时候立马执行;对应事件的类型是ApplicationStartedEvent
environmentPrepared() ApplicationContext创建之前并且环境信息准备好的时候调用;对应事件的类型是ApplicationEnvironmentPreparedEvent
contextPrepared() ApplicationContext创建好并且在source加载之前调用一次;没有具体的对应事件
contextLoaded() ApplicationContext创建并加载之后并在refresh之前调用;对应事件的类型是ApplicationPreparedEvent
finished() run方法结束之前调用;对应事件的类型是ApplicationReadyEvent或ApplicationFailedEven
SpringApplicationRunListeners是SpringApplicationRunListener的集合,SpringApplicationRunListener只有一个实现类:EventPublishingRunListener,在这个实现类中,有一个SimpleApplicationEventMulticaster类型的属性initialMulticaster,所有的事件都是通过这个属性的multicastEvent方法广播出去的。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值