您当前的位置: 首页 >  spring

星夜孤帆

暂无认证

  • 1浏览

    0关注

    626博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

SpringBoot源码解析-启动流程

星夜孤帆 发布时间:2021-07-10 12:18:18 ,浏览量:1

一、SpringApplication() 构造方法

SpringBoot项目的mian函数

@SpringBootApplication // 标注在类上说明这个类是SpringBoot的主配置类
@EnableRegisterService
public class SpringBootMyTestApplication {

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

}

 点进run方法

	public static ConfigurableApplicationContext run(Class primarySource, String... args) {
		// 调用重载方法
		return run(new Class[] { primarySource }, args);
	}
	public static ConfigurableApplicationContext run(Class[] primarySources, String[] args) {
		// 两件事:1.初始化SpringApplication 2.执行run方法
		return new SpringApplication(primarySources).run(args);
	}

继续查看源码, SpringApplication 实例化过程,首先是进入带参数的构造方法,最终回来到两个参数的构造方法。

	public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) {
		// 设置资源加载器为null
		this.resourceLoader = resourceLoader;
		// 断言加载资源类不能为null
		Assert.notNull(primarySources, "PrimarySources must not be null");
		// 将primarySources数组转换为List,最后放到LinkedHashSet集合中
		this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
		//【1.1 推断应用类型,后面会根据类型初始化对应的环境。常用的一般都是servlet环境 】
		this.webApplicationType = WebApplicationType.deduceFromClasspath();
		//【1.2 初始化classpath下 META-INF/spring.factories中已配置的ApplicationContextInitializer 】
		setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
		//【1.3 初始化classpath下所有已配置的 ApplicationListener 】
		setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
		//【1.4 根据调用栈,推断出 main 方法的类名 】
		this.mainApplicationClass = deduceMainApplicationClass();
	}
1.1 deduceFromClasspath()
public enum WebApplicationType {

	/**
	 * 应用程序不是web应用,也不应该用web服务器去启动
	 */
	NONE,

	/**
	 * 应用程序应作为基于servlet的web应用程序运行,并应启动嵌入式servlet web(tomcat)服务器。
	 */
	SERVLET,

	/**
	 * 应用程序应作为 reactive web应用程序运行,并应启动嵌入式 reactive web服务器。
	 */
	REACTIVE;

	private static final String[] SERVLET_INDICATOR_CLASSES = { "javax.servlet.Servlet",
			"org.springframework.web.context.ConfigurableWebApplicationContext" };

	private static final String WEBMVC_INDICATOR_CLASS = "org.springframework.web.servlet.DispatcherServlet";

	private static final String WEBFLUX_INDICATOR_CLASS = "org.springframework.web.reactive.DispatcherHandler";

	private static final String JERSEY_INDICATOR_CLASS = "org.glassfish.jersey.servlet.ServletContainer";

	private static final String SERVLET_APPLICATION_CONTEXT_CLASS = "org.springframework.web.context.WebApplicationContext";

	private static final String REACTIVE_APPLICATION_CONTEXT_CLASS = "org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext";

	/**
	 * 判断 应用的类型
	 * NONE: 应用程序不是web应用,也不应该用web服务器去启动
	 * SERVLET: 应用程序应作为基于servlet的web应用程序运行,并应启动嵌入式servlet web(tomcat)服务器。
	 * REACTIVE: 应用程序应作为 reactive web应用程序运行,并应启动嵌入式 reactive web服务器。
	 */
	static WebApplicationType deduceFromClasspath() {
		// classpath下必须存在org.springframework.web.reactive.DispatcherHandler
		if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
				&& !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
			return WebApplicationType.REACTIVE;
		}
		for (String className : SERVLET_INDICATOR_CLASSES) {
			if (!ClassUtils.isPresent(className, null)) {
				return WebApplicationType.NONE;
			}
		}
		// classpath环境下存在javax.servlet.Servlet或者org.springframework.web.context.ConfigurableWebApplicationContext
		return WebApplicationType.SERVLET;
	}

返回类型是WebApplicationType的枚举类型, WebApplicationType 有三个枚举,三个枚举的解释如其中注释

具体的判断逻辑如下:

WebApplicationType.REACTIVE classpath下存在org.springframework.web.reactive.DispatcherHandler

WebApplicationType.SERVLET classpath下存在javax.servlet.Servlet或者org.springframework.web.context.ConfigurableWebApplicationContext

WebApplicationType.NONE 不满足以上条件。

1.2 setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class))

初始化classpath下 META-INF/spring.factories中已配置的ApplicationContextInitializer

	// 通过指定的classloader 从META-INF/spring.factories获取指定的Spring的工厂实例
	private  Collection getSpringFactoriesInstances(Class type, Class[] parameterTypes, Object... args) {
		ClassLoader classLoader = getClassLoader();
		// Use names and ensure unique to protect against duplicates
		// 通过指定的classLoader从META-INF/spring.factories 的资源文件中,读取 key 为 type.getName() 的 value
		Set names = new LinkedHashSet(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
		// 创建Spring工厂实例
		List instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
		// 对Spring工厂实例排序(org.springframework.core.annotation.Order注解指定的顺序)
		AnnotationAwareOrderComparator.sort(instances);
		return instances;
	}

看看 getSpringFactoriesInstances 都干了什么,看源码,有一个方法很重要 loadFactoryNames()

这个方法很重要,这个方法是spring-core中提供的从META-INF/spring.factories中获取指定的类(key)的同一入口方法。

在这里,获取的是key为 org.springframework.context.ApplicationContextInitializer 的类。 

debug看看都获取到了哪些

 

ApplicationContextInitializer 是Spring框架的类, 这个类的主要目的就是在ConfigurableApplicationContext 调用refresh()方法之前,回调这个类的initialize方法。

通过ConfigurableApplicationContext 的实例获取容器的环境Environment,从而实现对配置文件的修改完善等工作。

1.3 setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class))

初始化classpath下 META-INF/spring.factories中已配置的 ApplicationListener。

ApplicationListener 的加载过程和上面的 ApplicationContextInitializer 类的加载过程是一样的,不多说了。

至于 ApplicationListener 是spring的事件监听器,典型的观察者模式,通过ApplicationEvent 类和 ApplicationListener 接口,可以实现对spring容器全生命周期的监听,

当然也可以自定义监听事件

1.4 总结

关于 SpringApplication 类的构造过程,到这里我们就梳理完了。

纵观 SpringApplication 类的实例化过程,我们可以看到,合理的利用该类,我们能在spring容器创建之前做一些预备工作,和定制化的需求。

比如,自定义SpringBoot的Banner,比如自定义事件监听器,再比如在容器refresh之前通过自定义ApplicationContextInitializer 修改配置一些配置或者获取指定的bean都是可以的

二、Run(args)

 

 

上一小节我们查看了SpringApplication 类的实例化过程,这一小节总结SpringBoot启动流程最重要的部分run方法。

通过run方法梳理出SpringBoot启动的流程,经过深入分析后,大家会发现SpringBoot也就是给Spring包了一层皮,事先替我们准备好Spring所需要的环境及一些基础。

/**
	 * 启动过程中的重要步骤共分为六步
	 * 第一步:获取并启动监听器
	 * 第二步:构造应用上下文环境
	 * 第三步:初始化应用上下文
	 * 第四步:刷新应用上下文前的准备阶段
	 * 第五步:刷新应用上下文
	 * 第六步:刷新应用上下文后的扩展接口
	 *
	 * 运行spring应用,并刷新一个新的 ApplicationContext(Spring的上下文)
	 * ConfigurableApplicationContext 是 ApplicationContext 接口的子接口。
	 * 在ApplicationContext基础上增加了配置上下文的工具。 ConfigurableApplicationContext是容器的高级接口
	 */
	public ConfigurableApplicationContext run(String... args) {
		// 记录程序运行时间
		// StopWatch主要是用来统计每项任务执行时长,例如Spring Boot启动占用总时长。
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		// ConfigurableApplicationContext Spring 的上下文
		ConfigurableApplicationContext context = null;
		Collection exceptionReporters = new ArrayList();
		configureHeadlessProperty();
		// 从META-INF/spring.factories中获取监听器
 		// 1、获取并启动监听器
		// 第一步:获取并启动监听器 通过加载META-INF/spring.factories 完成了SpringApplicationRunListener实例化工作
		SpringApplicationRunListeners listeners = getRunListeners(args);
		// 实际上是调用了EventPublishingRunListener类的starting()方法
		listeners.starting();
		try {
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
			// 2、构造应用上下文环境
			// 第二步:构造容器环境,简而言之就是加载系统变量,环境变量,配置文件
			ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
			// 处理需要忽略的Bean
			configureIgnoreBeanInfo(environment);
			// 打印banner
			Banner printedBanner = printBanner(environment);
			// 3、初始化应用上下文
			// 第三步:创建容器
			context = createApplicationContext();
			// 实例化SpringBootExceptionReporter.class,用来支持报告关于启动的错误
			// 第四步:实例化SpringBootExceptionReporter.class,用来支持报告关于启动的错误
			exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
					new Class[] { ConfigurableApplicationContext.class }, context);
			// 4、刷新应用上下文前的准备阶段
			// 第五步:准备容器 这一步主要是在容器刷新之前的准备动作。包含一个非常关键的操作:将启动类注入容器,为后续开启自动化配置奠定基础。
			prepareContext(context, environment, listeners, applicationArguments, printedBanner);
			// 5、刷新应用上下文(IOC容器的初始化过程)
			// 第六步:刷新容器 springBoot相关的处理工作已经结束,接下的工作就交给了spring。内部会调用spring的refresh方法,
			// refresh方法在spring整个源码体系中举足轻重,是实现 ioc 和 aop的关键。
			refreshContext(context);
			// 刷新应用上下文后的扩展接口
			// 第七步:刷新容器后的扩展接口 设计模式中的模板方法,默认为空实现。如果有自定义需求,可以重写该方法。比如打印一些启动结束log,或者一些其它后置处理。
			afterRefresh(context, applicationArguments);
			// 时间记录停止
			stopWatch.stop();
			if (this.logStartupInfo) {
				new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
			}
			// 发布容器启动完成事件
			listeners.started(context);
			// 遍历所有注册的ApplicationRunner和CommandLineRunner,并执行其run()方法。
			// 我们可以实现自己的ApplicationRunner或者CommandLineRunner,来对SpringBoot的启动过程进行扩展。
			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;
	}

在以上的代码中,启动过程中的重要步骤共分为六步

第一步:获取并启动监听器

第二步:构造应用上下文环境

第三步:初始化应用上下文

第四步:刷新应用上下文前的准备阶段

第五步:刷新应用上下文

第六步:刷新应用上下文后的扩展接口

OK,下面SpringBoot的启动流程分析,我们就根据这6大步骤进行详细解读。最重要的是第四,五步。我们会着重的分析。

2.1 第一步:获取并启动监听器

事件机制在Spring中是很重要的一部分内容,通过事件机制我们可以监听Spring容器中正在发生的一些事件,同样也可以自定义监听事件。

Spring的事件为Bean和Bean之间的消息传递提供支持。

当一个对象处理完某种任务后,通知另外的对象进行某些处理,常用的场景有进行某些操作后发送通知,消息、邮件等情况。

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

在这里面是不是看到一个熟悉的方法:getSpringFactoriesInstances(),可以看下面的注释,

前面的小节我们已经详细介绍过该方法是怎么一步步的获取到META-INF/spring.factories中的指定的key的value,获取到以后怎么实例化类的。

	// 通过指定的classloader 从META-INF/spring.factories获取指定的Spring的工厂实例
	private  Collection getSpringFactoriesInstances(Class type, Class[] parameterTypes, Object... args) {
		ClassLoader classLoader = getClassLoader();
		// Use names and ensure unique to protect against duplicates
		// 通过指定的classLoader从META-INF/spring.factories 的资源文件中,读取 key 为 type.getName() 的 value
		Set names = new LinkedHashSet(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
		// 创建Spring工厂实例
		List instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
		// 对Spring工厂实例排序(org.springframework.core.annotation.Order注解指定的顺序)
		AnnotationAwareOrderComparator.sort(instances);
		return instances;
	}

回到run方法,debug这个代码 SpringApplicationRunListeners listeners = getRunListeners(args);

看一下获取的是哪个监听器: 

  

 

EventPublishingRunListener监听器是Spring容器的启动监听器。

listeners.starting(); 开启了监听事件。

 2.2 构造应用上下文环境

应用上下文环境包括什么呢?

包括计算机的环境,Java环境,Spring的运行环境,Spring项目的配置(在SpringBoot中就是那个熟悉的application.properties/yaml)等等。

首先看一下prepareEnvironment()方法。

	private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
			ApplicationArguments applicationArguments) {
		// Create and configure the environment
		// 创建并配置相应的环境
		ConfigurableEnvironment environment = getOrCreateEnvironment();
		// 根据用户配置,配置 environment系统环境
		configureEnvironment(environment, applicationArguments.getSourceArgs());
		ConfigurationPropertySources.attach(environment);
		// 启动相应的监听器,其中一个重要的监听器 ConfigFileApplicationListener 就是加载项目配置文件的监听器。
		listeners.environmentPrepared(environment);
		bindToSpringApplication(environment);
		if (!this.isCustomEnvironment) {
			environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment,
					deduceEnvironmentClass());
		}
		ConfigurationPropertySources.attach(environment);
		return environment;
	}

看上面的注释,方法中主要完成的工作,首先是创建并按照相应的应用类型配置相应的环境,

然后根据用户的配置,配置系统环境,

然后启动监听器,并加载系统配置文件。

2.2.1 ConfigurableEnvironment environment = getOrCreateEnvironment()

看看getOrCreateEnvironment()干了些什么

	private ConfigurableEnvironment getOrCreateEnvironment() {
		if (this.environment != null) {
			return this.environment;
		}
		switch (this.webApplicationType) {
		// 如果应用类型是 SERVLET 则实例化 StandardServletEnvironment
		case SERVLET:
			return new StandardServletEnvironment();
		case REACTIVE:
			return new StandardReactiveWebEnvironment();
		default:
			return new StandardEnvironment();
		}
	}

通过代码可以看到根据不同的应用类型初始化不同的系统环境实例。

前面咱们已经说过应用类型是怎么判断的了,这里就不在赘述了

从上面的继承关系可以看出,StandardServletEnvironment是StandardEnvironment的子类。

这两个对象也没什么好讲的,当是web项目的时候,环境上会多一些关于web环境的配置。

2.2.2 configureEnvironment(environment, applicationArguments.getSourceArgs())
	protected void configureEnvironment(ConfigurableEnvironment environment, String[] args) {
		if (this.addConversionService) {
			ConversionService conversionService = ApplicationConversionService.getSharedInstance();
			environment.setConversionService((ConfigurableConversionService) conversionService);
		}
		// 将main 函数的args封装成 SimpleCommandLinePropertySource 加入环境中。
		configurePropertySources(environment, args);
		// 激活相应的配置文件
		configureProfiles(environment, args);
	}

 

在configurePropertySources(environment, args);中将args封装成了SimpleCommandLinePropertySource并加入到了environment中。

在configureProfiles(environment, args);中根据启动参数激活了相应的配置文件。

2.2.3 listeners.environmentPrepared(environment)

进入到方法一路跟下去就到了SimpleApplicationEventMulticaster类的multicastEvent()方法。

查看getApplicationListeners(event, type)执行结果,发现一个重要的监听器ConfigFileApplicationListener。

先看看这个类的注释

/**
 * {@link EnvironmentPostProcessor} that configures the context environment by loading
 * properties from well known file locations. By default properties will be loaded from
 * 'application.properties' and/or 'application.yml' files in the following locations:
 * 从这几个位置加载配置文件,并将其加入上下文的environment变量中
 * 当然也可以通过配置指定
 * 
    *
  • file:./config/
  • *
  • file:./
  • *
  • classpath:config/
  • *
  • classpath:
  • *
* The list is ordered by precedence (properties defined in locations higher in the list * override those defined in lower locations). *

* Alternative search locations and names can be specified using * {@link #setSearchLocations(String)} and {@link #setSearchNames(String)}. *

* Additional files will also be loaded based on active profiles. For example if a 'web' * profile is active 'application-web.properties' and 'application-web.yml' will be * considered. *

* The 'spring.config.name' property can be used to specify an alternative name to load * and the 'spring.config.location' property can be used to specify alternative search * locations or specific files. *

* * 从默认的位置加载配置文件,将其加入上下文的environment变量中 * */

这个监听器默认从注释中

标签所示的几个位置加载配置文件,并将其加入上下文的 environment变量中。

当然也可以通过配置指定。

debug跳过 listeners.environmentPrepared(environment); 这一行,查看environment属性,果真如上面所说的,配置文件的配置信息已经添加上来了。

 2.3 第三步:初始化应用上下文

在SpringBoot工程中,应用类型分为三种,如下代码所示。

public enum WebApplicationType {

	/**
	 * The application should not run as a web application and should not start an
	 * embedded web server.
	 *
	 * 应用程序不是web应用,也不应该用web服务器去启动
	 */
	NONE,

	/**
	 * The application should run as a servlet-based web application and should start an
	 * embedded servlet web server.
	 *
	 * 应用程序应作为基于servlet的web应用程序运行,并应启动嵌入式servlet web(tomcat)服务器。
	 */
	SERVLET,

	/**
	 * The application should run as a reactive web application and should start an
	 * embedded reactive web server.
	 *
	 * 应用程序应作为 reactive web应用程序运行,并应启动嵌入式 reactive web服务器。
	 */
	REACTIVE;
}

对应三种应用类型,SpringBoot项目有三种对应的应用上下文,我们以web工程为例,即其上下文为AnnotationConfigServletWebServerApplicationContext。

public class SpringApplication {

	protected ConfigurableApplicationContext createApplicationContext() {
		Class contextClass = this.applicationContextClass;
		if (contextClass == null) {
			try {
				switch (this.webApplicationType) {
				case SERVLET:
					// AnnotationConfigServletWebServerApplicationContext
					contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
					break;
				case REACTIVE:
					// AnnotationConfigReactiveWebServerApplicationContext
					contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
					break;
				default:
					// AnnotationConfigApplicationContext
					contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
				}
			}
			catch (ClassNotFoundException ex) {
				throw new IllegalStateException(
						"Unable create a default ApplicationContext, please specify an ApplicationContextClass", ex);
			}
		}
		// 不但初始化了AnnotationConfigServletWebServerApplicationContext类,也就是我们的上下文context
		// 同样也触发了GenericApplicationContext类的构造函数,从而IoC容器也创建了。
		return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
	}
}

我们先看一下AnnotationConfigServletWebServerApplicationContext的设计

应用上下文可以理解成IoC容器的高级表现形式,应用上下文确实是在IoC容器的基础上丰富了一些高级功能。

应用上下文对IoC容器是持有的关系。他的一个属性beanFactory就是IoC容器(DefaultListableBeanFactory)。

所以他们之间是持有,和扩展的关系。

接下来看GenericApplicationContext类

beanFactory正是在AnnotationConfigServletWebServerApplicationContext实现的接口GenericApplicationContext中定义的。

在上面createApplicationContext()方法中的,BeanUtils.instantiateClass(contextClass) 这个方法中,不但初始化了AnnotationConfigServletWebServerApplicationContext类,

也就是我们的上下文context,同样也触发了GenericApplicationContext类的构造函数,从而IoC容器也创建了。

仔细看他的构造函数,有没有发现一个很熟悉的类DefaultListableBeanFactory,没错,DefaultListableBeanFactory就是IoC容器真实面目了。

在后面的refresh()方法分析中,DefaultListableBeanFactory是无处不在的存在感。

debug跳过createApplicationContext()方法。

如上图所示,context就是我们熟悉的上下文(也有人称之为容器,都可以,看个人爱好和理解),beanFactory就是我们所说的IoC容器的真实面孔了。

细细感受下上下文和容器的联系和区别,对于我们理解源码有很大的帮助。

在我们学习过程中,我们也是将上下文和容器严格区分开来的。

2.4 第四步:刷新应用上下文前的准备阶段 2.4.1 prepareContext()方法

前面我们介绍了SpringBoot 启动流程run()方法的前三步,接下来再来介绍:

第四步:刷新应用上下文前的准备阶段。也就是prepareContext()方法。

首先看prepareContext()方法。

	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);
		if (this.logStartupInfo) {
			logStartupInfo(context.getParent() == null);
			logStartupProfileInfo(context);
		}
		// Add boot specific singleton beans
		// 将main函数中的args参数封装成单例Bean,注册进容器
		ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
		beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
		// 将 printedBanner 也封装成单例,注册进容器
		if (printedBanner != null) {
			beanFactory.registerSingleton("springBootBanner", printedBanner);
		}
		if (beanFactory instanceof DefaultListableBeanFactory) {
			((DefaultListableBeanFactory) beanFactory)
					.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
		}
		if (this.lazyInitialization) {
			context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
		}
		// Load the sources
		Set sources = getAllSources();
		Assert.notEmpty(sources, "Sources must not be empty");
		// 加载我们的启动类,将启动类注入容器
		load(context, sources.toArray(new Object[0]));
		// 发布容器已加载事件
		listeners.contextLoaded(context);
	}

首先看这行 Set sources = getAllSources();

在getAllSources()中拿到了我们的启动类。

我们重点讲解这行 load(context, sources.toArray(new Object[0])); ,其他的方法请参阅注释。

跟进load()方法,看源码

	protected void load(ApplicationContext context, Object[] sources) {
		if (logger.isDebugEnabled()) {
			logger.debug("Loading source " + StringUtils.arrayToCommaDelimitedString(sources));
		}
		//创建 BeanDefinitionLoader
		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();
	}
2.4.2 getBeanDefinitionRegistry()

继续看getBeanDefinitionRegistry()方法的源码

	private BeanDefinitionRegistry getBeanDefinitionRegistry(ApplicationContext context) {
		// 将我们前文创建的上下文强转为BeanDefinitionRegistry,他们之间是有继承关系的。
		if (context instanceof BeanDefinitionRegistry) {
			return (BeanDefinitionRegistry) context;
		}
		if (context instanceof AbstractApplicationContext) {
			return (BeanDefinitionRegistry) ((AbstractApplicationContext) context).getBeanFactory();
		}
		throw new IllegalStateException("Could not locate BeanDefinitionRegistry");
	}

这里将我们前文创建的上下文强转为BeanDefinitionRegistry,他们之间是有继承关系的。

BeanDefinitionRegistry定义了很重要的方法registerBeanDefinition(),该方法将BeanDefinition注册进DefaultListableBeanFactory容器的beanDefinitionMap中。

2.4.3 createBeanDefinitionLoader()

继续看createBeanDefinitionLoader()方法,最终进入了BeanDefinitionLoader类的构造方法,如下

	BeanDefinitionLoader(BeanDefinitionRegistry registry, Object... sources) {
		Assert.notNull(registry, "Registry must not be null");
		Assert.notEmpty(sources, "Sources must not be empty");
		this.sources = sources;
		// 注解形式的Bean定义读取器 比如:@Configuration @Bean @Component @Controller @Service等等
		this.annotatedReader = new AnnotatedBeanDefinitionReader(registry);
		// XML形式的Bean定义读取器
		this.xmlReader = new XmlBeanDefinitionReader(registry);
		if (isGroovyPresent()) {
			this.groovyReader = new GroovyBeanDefinitionReader(registry);
		}
		// 类路径扫描器
		this.scanner = new ClassPathBeanDefinitionScanner(registry);
		// 扫描器添加排除过滤器
		this.scanner.addExcludeFilter(new ClassExcludeFilter(sources));
	}

先记住上面的三个属性,上面三个属性在,BeanDefinition的Resource定位,和BeanDefinition的注册中起到了很重要的作用。

2.4.4 loader.load();

跟进load()方法

private int load(Object source) {
		Assert.notNull(source, "Source must not be null");
		// 从Class加载,当前我们的主类会按Class加载。
		if (source instanceof Class) {
			return load((Class) source);
		}
		// 从Resource加载
		if (source instanceof Resource) {
			return load((Resource) source);
		}
		// 从Package加载
		if (source instanceof Package) {
			return load((Package) source);
		}
		// 从 CharSequence加载
		if (source instanceof CharSequence) {
			return load((CharSequence) source);
		}
		throw new IllegalArgumentException("Invalid source type " + source.getClass());
	}

当前我们的主类会按Class加载。

继续跟进load()方法。

	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);
		}
		// 判断主类是不是存在@Component注解,主类@SpringBootApplication是一个组合注解,包含@Component。
		if (isComponent(source)) {
			// 将启动类的BeanDefinition注册进beanDefinitionMap
			this.annotatedReader.register(source);
			return 1;
		}
		return 0;
	}

isComponent(source)判断主类是不是存在@Component注解,主类@SpringBootApplication是一个组合注解,包含@Component。

this.annotatedReader.register(source);跟进register()方法,最终进到AnnotatedBeanDefinitionReader类的doRegisterBean()方法。

	public void register(Class... componentClasses) {
		for (Class componentClass : componentClasses) {
			registerBean(componentClass);
		}
	}
 void doRegisterBean(Class annotatedClass, @Nullable Supplier instanceSupplier, @Nullable String name,
			@Nullable Class            
关注
打赏
1636984416
查看更多评论
0.0446s