public ConfigurableApplicationContext run(String... args) {
// StopWatch用来计时的, 我们也可以拿来使用
StopWatch stopWatch = new StopWatch();
// 开启计时
stopWatch.start();
// spring应用上下文
ConfigurableApplicationContext context = null;
// 异常报告解析器集合
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
// 根据系统属性"java.awt.headless", 选择是否激活headless模式(默认激活)
configureHeadlessProperty();
// 使用SpringFactoriesLoader加载META-INF/spring.factories文件
// 中SpringApplicationRunListener全类名所对应的所有类,
// 并实例化返回, 封装到SpringApplicationRunListeners中
SpringApplicationRunListeners listeners = getRunListeners(args);
// 回调刚刚加载的所有SpringApplicationRunListener的监听器的starting方法, 表示要开始启动了
listeners.starting();
try {
// 封装命令行参数args到ApplicationArguments (内部使用SimpleCommandLineArgsParser解析命令行参数), 格式为: --foo=bar
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
// 创建并准备Environment
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
// 配置系统属性"spring.beaninfo.ignore"
configureIgnoreBeanInfo(environment);
// 打印banner
Banner printedBanner = printBanner(environment);
// 创建spring容器(应用上下文)
context = createApplicationContext();
// 使用SpringFactoriesLoader加载META-INFO/spring.factories文件中SpringBootExceptionReporter全类名, 所配置的值, 全部实例化,默认有FailureAnalyzers
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,new Class[] {ConfigurableApplicationContext.class }, context);
// 准备spring容器(应用上下文)
// 1. context设置env
// 2. beanFactory设置conversionService
// 3. 应用ApplicationContextInitializer(上一章实例化的初始化器)
// 4. 通知所有SpringApplicationRunListener的contextPrepared(ConfigurableApplicationContext)方法回调
// 5. 日志打印激活的profile
// 6. 注册单例: "springApplicationArguments"-applicationArguments命令行参数封装对象
// 7. 注册单例: "springBootBanner"-springBootBanner
// 8. 使用SpringApplication的allowBeanDefinitionOverriding属性,覆盖beanFactory的allowBeanDefinitionOverriding属性值, 决定是否允许bean定义覆盖
// 9. 默认不注册LazyInitializationBeanFactoryPostProcessor后置处理器, 但可以打开(但要求提供一个LazyInitializationExcludeFilter的bean)
// 10. 载入SpringApplication的primarySources属性(入口类)和sources属性(可添加类名、包名、xml文件)的资源, 读取其中的beanDefinition定义信息, 并注册到BeanFactory工厂中
// 11. 通知所有SpringApplicationRunListener的contextLoaded(ConfigurableApplicationContext)方法回调(注意此时容器还并未刷新)
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// 经典的spring容器refresh刷新操作(spring容器的核心操作), 前面都是在做准备工作
refreshContext(context);
// 容器刷新后的操作(默认空方法)
afterRefresh(context, applicationArguments);
// 停止计时
stopWatch.stop();
// 日志打印启动花费事件
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
// 通知所有SpringApplicationRunListener的started(ConfigurableApplicationContext)方法回调, 告诉监听器: 容器已经启动啦
listeners.started(context);
// 获取spring容器中的ApplicationRunner和CommandLineRunner并根据@Order和Order接口排序, 挨个回调它们的run方法
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
// 但凡以上操作发生任何异常或错误, 通知所有SpringApplicationRunListener的failed(context,exception)方法回调, 告诉监听器: 启动失败啦
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
// 通知所有SpringApplicationRunListener的running(context,exception)方法回调, 告诉监听器: 容器正在运行
listeners.running(context);
}
catch (Throwable ex) {
// 但凡以上操作发生任何异常或错误, 通知所有SpringApplicationRunListener的failed(context,exception)方法回调, 告诉监听器: 启动失败啦
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}
private SpringApplicationRunListeners getRunListeners(String[] args) {
// SpringApplicationRunListener的指定构造参数的构造器
// 第一个构造参数是: SpringApplication.class
// 第二个构造参数类型是: String[].class
// 所以自定义SpringApplicationRunListener类时, 需要创建此构造参数类型的构造器
// 之后, 我们同样可以在resources目录下创建META-INF/spring.factories文件, 在里面配置自定义的SpringApplicationRunListener类
Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
return new SpringApplicationRunListeners(logger,getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args));
}
SpringApplication运行的监听器,内部维护了一堆的SpringApplicationRunListener,它们会在SpringApplication运行的各个阶段的不同时机回调对应的方法。
starting —> 创建并准备环境env—>environmentPrepared—>创建spring容器应用上下文—>contextPrepared—>spring容器应用上下文加载资源(sources)—>contextLoaded—>spring容器应用上下文刷新—>started—>ApplicationRunner和CommandLineRunner运行run方法—>running
[发生异常, 则调用failed]
public interface SpringApplicationRunListener {
// 当SpringApplication的run方法刚运行, 并且刚刚实例化了SpringApplicationRunListener时, 调用starting
default void starting() {}
// 当ConfigurableEnvironment对象刚被创建好时, 调用 environmentPrepared
default void environmentPrepared(ConfigurableEnvironment environment) {}
// 当spring容器应用上下文创建好, 并且已经设置了env, 也应用了ApplicationContextInitializer时, 调用contextPrepared
default void contextPrepared(ConfigurableApplicationContext context) {}
// 当spring容器应用上下文刚加载primarySources和sources中的bean定义信息后, 调用contextLoaded
default void contextLoaded(ConfigurableApplicationContext context) {}
// 当spring容器应用上下文刷新完成之后, 但是在ApplicationRunner和CommandLineRunner调用之前, 调用started
default void started(ConfigurableApplicationContext context) {}
// 在ApplicationRunner和CommandLineRunner调用之后, 调用running
default void running(ConfigurableApplicationContext context) {}
// 在发生异常时, 调用running
default void failed(ConfigurableApplicationContext context, Throwable exception) {}
}
在springboot中,在spring.factories文件中,默认为我们配置了SpringApplicationRunListener
public class EventPublishingRunListener implements SpringApplicationRunListener, Ordered {
private final SpringApplication application;
private final String[] args;
private final SimpleApplicationEventMulticaster initialMulticaster;
// 如前所述, 它必须有这样一个构造参数类型的构造器
public EventPublishingRunListener(SpringApplication application, String[] args) {
this.application = application; // SpringApplication实例
this.args = args; // 命令行参数
// 创建了一个SimpleApplicationEventMulticaster,设置为多播器属性
this.initialMulticaster = new SimpleApplicationEventMulticaster();
// 获取到SpringApplication中的所有ApplicationListner监听器
// 注意: 是应用监听器, 而不是SpringApplicationRunListener监听器
// 应用监听器, 它默认在创建SpringApplication实例时(上一章), 从spring.factories文件中, 实例化ApplicationListener全类名对应的所有类
// (也可以手动添加进去)
for (ApplicationListener<?> listener : application.getListeners()) {
// 将所有的应用监听器全部添加到SimpleApplicationEventMulticaster多播器中
// 这样应用发布事件就可以委托给这个多播器了
this.initialMulticaster.addApplicationListener(listener);
}
}
@Override
public int getOrder() {
return 0; // 顺序是0,
}
@Override
public void starting() {
// 委托给多播器发布 ApplicationStartingEvent 事件
// (所以,此时应用监听器可以在starting时机, 收到该事件)
this.initialMulticaster.multicastEvent(new ApplicationStartingEvent(this.application, this.args));
}
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
// 委托给多播器发布 ApplicationEnvironmentPreparedEvent事件
// (所以,此时应用监听器可以在environmentPrepared时机, 收到该事件)
this.initialMulticaster.multicastEvent(new ApplicationEnvironmentPreparedEvent(this.application, this.args, environment));
}
@Override
public void contextPrepared(ConfigurableApplicationContext context) {
// 委托给多播器发布 ApplicationEnvironmentPreparedEvent事件
// (所以,此时应用监听器可以在contextPrepared时机, 收到该事件)
this.initialMulticaster.multicastEvent(new ApplicationContextInitializedEvent(this.application, this.args, context));
}
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
// 当SpringApplicationRunListner收到contextLoaded上下文资源已加载后,
// 就把所有的应用监听器, 都交给了Spring应用上下文, 因为资源已经加载好了, 下一步就要刷新容器了,
// 这个时候应用监听器要去监听spring容器内部的事件了
// 同时这里也是最后一次委托多播器去发布ApplicationPreparedEvent事件了
// 后面发布事件就由spring应用上下文自己来发布使劲按
for (ApplicationListener<?> listener : this.application.getListeners()) {
// 如果应用上下文还实现了ApplicationContextAware, 就会将context设置给它
if (listener instanceof ApplicationContextAware) {
((ApplicationContextAware) listener).setApplicationContext(context);
}
context.addApplicationListener(listener);
}
// 委托多播器发布ApplicationPreparedEvent事件
this.initialMulticaster.multicastEvent(new ApplicationPreparedEvent(this.application, this.args, context));
}
@Override
public void started(ConfigurableApplicationContext context) {
// spring应用刷新完成后, 使用context发布ApplicationStartedEvent事件, 此时context内部的应用监听器会收到此事件
// 我们也可以拿到context之后, 自己调用publisEvent手动发布事件
context.publishEvent(new ApplicationStartedEvent(this.application, this.args, context));
}
@Override
public void running(ConfigurableApplicationContext context) {
// 调用完ApplicationRunner和CommandLineRunner的run方法后,
// 继续调用context发布ApplicationReadyEvent事件
context.publishEvent(new ApplicationReadyEvent(this.application, this.args, context));
}
@Override
public void failed(ConfigurableApplicationContext context, Throwable exception) {
ApplicationFailedEvent event = new ApplicationFailedEvent(this.application, this.args, context, exception);
if (context != null && context.isActive()) {
// Listeners have been registered to the application context so we should
// use it at this point if we can
// 发布应用启动失败事件
context.publishEvent(event);
}
else {
// An inactive context may not have a multicaster so we use our multicaster to
// call all of the context's listeners instead
if (context instanceof AbstractApplicationContext) {
for (ApplicationListener<?> listener : ((AbstractApplicationContext) context)
.getApplicationListeners()) {
this.initialMulticaster.addApplicationListener(listener);
}
}
this.initialMulticaster.setErrorHandler(new LoggingErrorHandler());
this.initialMulticaster.multicastEvent(event);
}
}
}
用于提供访问运行SpringApplication时的参数,
DefaultApplicationArguments实现了ApplicationArguments接口,它实现该接口的方式,就是通过委托给静态内部类对象Source(间接实现了PropertySource接口,该接口解析见spring属性配置文件解析&类型转换)实现的。
public class DefaultApplicationArguments implements ApplicationArguments {
// Source是DefaultApplicationArguments中定义的静态内部类,
// 继承自SimpleCommandLinePropertySource,
// 所以也是一种PropertySource, 泛型是CommandLineArgs, 所以PropertySource的source属性是CommandLineArgs类型的
// 看到下面的实现, 又是委托给了PropertySource的source属性去实现了
// 所以实现相当于交给了CommandLineArgs了
private final Source source;
private final String[] args;
public DefaultApplicationArguments(String... args) {
Assert.notNull(args, "Args must not be null");
this.source = new Source(args);
this.args = args;
}
@Override
public String[] getSourceArgs() {
// 返回原来传过来的args
return this.args;
}
@Override
public Set<String> getOptionNames() {
// 委托给了静态内部类对象的source属性
String[] names = this.source.getPropertyNames();
return Collections.unmodifiableSet(new HashSet<>(Arrays.asList(names)));
}
@Override
public boolean containsOption(String name) {
// 委托给了静态内部类对象的source属性
return this.source.containsProperty(name);
}
@Override
public List<String> getOptionValues(String name) {
// 委托给了静态内部类对象的source属性
List<String> values = this.source.getOptionValues(name);
return (values != null) ? Collections.unmodifiableList(values) : null;
}
@Override
public List<String> getNonOptionArgs() {
// // 委托给了静态内部类对象的source属性
return this.source.getNonOptionArgs();
}
private static class Source extends SimpleCommandLinePropertySource {
Source(String[] args) {
// 交给父类SimpleCommandLinePropertySource解析arg
// (父类使用new SimpleCommandLineArgsParser().parse(args)返回CommandLineArgs)
// 将返回的CommandLineArgs作为PropertySource的source属性源
// 注意: 父类SimpleCommandLinePropertySource定义了PropertySource的泛型为
super(args);CommandLineArgs
}
@Override
public List<String> getNonOptionArgs() {
return super.getNonOptionArgs();
}
@Override
public List<String> getOptionValues(String name) {
return super.getOptionValues(name);
}
}
}
public interface ApplicationArguments {
// 就是 入口类 传入的字符串参数
String[] getSourceArgs();
// 运行参数集合, 如: "--foo=bar --debug", 会返回["foo", "debug"]
Set<String> getOptionNames();
// 是否包含指定的运行参数name
boolean containsOption(String name);
// 获取指定运行参数name所对应的值集合, 如"--foo=bar --foo=baz", 会返回["bar", "baz"]
List<String> getOptionValues(String name);
// 获取没有设置运行参数值的运行参数名集合
List<String> getNonOptionArgs();
}
准备环境,返回ConfigurableEnvironment接口实例对象,它继承了Environment接口和ConfigurablePropertyResolver,间接继承了PropertyResolver接口。详情见:spring属性配置文件解析&类型转换
public interface ConfigurableEnvironment extends Environment, ConfigurablePropertyResolver {
// 设置默认激活的profiles组
void setActiveProfiles(String... profiles);
// 添加激活的profiles
void addActiveProfile(String profile);
// 设置默认的profiles组
void setDefaultProfiles(String... profiles);
// 属性源集合(封装多个属性源, 每个属性源有自己的名字和source)
MutablePropertySources getPropertySources();
// 获取系统属性
Map<String, Object> getSystemProperties();
// 获取系统环境
Map<String, Object> getSystemEnvironment();
// 合并指定环境中的配置到当前环境
void merge(ConfigurableEnvironment parent);
}
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,ApplicationArguments applicationArguments) {
// 创建环境对象(根据webApplicationType类型创建对应的环境对象, 如果已被设置,那就直接用设置好的)
ConfigurableEnvironment environment = getOrCreateEnvironment();
// 1. 给env设置类型转换服务(ApplicationConversionService.getSharedInstance())
// 2. 添加SpringApplication的defaultProperties属性, 封装成MapPropertySource, 添加到env中
// 3. 默认将命令行参数添加到env的“第一个”propertySource(说明命令行参数高优先级)
// 4. env合并SpringApplication的additionalProfiles和env自己的activeProfiles(spring.profiles.active配置的属性,
// 但是注意这个时候还没有加载配置文件呢!)作为env自己的activeProfiles
configureEnvironment(environment, applicationArguments.getSourceArgs());
// 添加了一个ConfigurationPropertySourcesPropertySource放在第一个, 但是内部还是委托给了env原来的sources中找
ConfigurationPropertySources.attach(environment);
// 通知所有的SpringApplicationRunListener环境对象已经准备好了, 调用它们的environmentPrepared方法
// (注意这里面有个ConfigFileApplicationListener监听器, 它在监听environmentPrepared事件时
// 也是通过SPI加载PropertySourceLoader(有PropertiesPropertySourceLoader和YamlPropertySourceLoader)
// 可以通过spring.config.location指定配置文件所在位置, 默认从classpath:/,classpath:/config/,file:./,file:./config/中找
// 默认找的名字是application, 可以通过spring.config.name指定名字)
// PropertySourceLoader指定了找的文件名后缀是properties和yml
listeners.environmentPrepared(environment);
// 将env绑定到SpringApplication实例
bindToSpringApplication(environment);
// 如果在SpringApplication实例中设置了env,那就是自定义了环境对象, 转换环境类型
if (!this.isCustomEnvironment) {
environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment,deduceEnvironmentClass());
}
// 移除添加的ConfigurationPropertySourcesPropertySource
ConfigurationPropertySources.attach(environment);
return environment;
}
打印banner,先添加图片banner(可通过spring.banner.image.location来指定,如果未指定,直接找banner.gif、banner.jpg、banner.png),再添加文字banner(可通过spring.banner.location指定banner的位置,如果未指定,默认找banner.txt)
private Banner printBanner(ConfigurableEnvironment environment) {
// 可以设置SpringApplication的bannerMode来关闭banner
if (this.bannerMode == Banner.Mode.OFF) {
return null;
}
// 默认使用DefaultResourceLoader资源加载器
ResourceLoader resourceLoader = (this.resourceLoader != null) ? this.resourceLoader: new DefaultResourceLoader(getClassLoader());
SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(resourceLoader, this.banner);
if (this.bannerMode == Mode.LOG) {
return bannerPrinter.print(environment, this.mainApplicationClass, logger);
}
return bannerPrinter.print(environment, this.mainApplicationClass, System.out);
}
创建应用上下文对象
protected ConfigurableApplicationContext createApplicationContext() {
// 可手动指定SpringApplication的applicationContextClass属性
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
// 根据之前推断出来的应用类型, 来选择不同的上下文class
switch (this.webApplicationType) {
case SERVLET:
// org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext
// 【所以默认情况下上下文对象是: AnnotationConfigServletWebServerApplicationContext】
// 它作为ApplicationContext的具体实现, 定义了很多的扩展实现
// 首先它继承自GenericApplicationContext, 在无参构造方法里, 就创建了DefaultListableBeanFactory作为beanFactory工厂
contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
break;
case REACTIVE:
// org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext
contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
break;
default:
// org.springframework.context.annotation.AnnotationConfigApplicationContext
contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
}
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Unable create a default ApplicationContext, please specify an ApplicationContextClass", ex);
}
}
// 使用反射创建容器上下文
return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}
准备应用上下文
private void prepareContext(ConfigurableApplicationContext context,
ConfigurableEnvironment environment,
SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments,
Banner printedBanner) {
// 将env设置到spring应用上下文
context.setEnvironment(environment);
// 空方法(可扩展)
postProcessApplicationContext(context);
// 将SpringApplication的ApplicatonContextInitlizer(前面通过SpringFactoriesLoader加载实例化的,或手动添加的)
// 应用到context上(初始化context)
applyInitializers(context);
// 通知所有的SpringApplicationRunListener监听器, 上下文对象已准备好
listeners.contextPrepared(context);
// 打印启动信息:
// INFO 12556 --- [main] com.zzhua.TestApplication: Starting TestApplication on
// INFO 12556 --- [main] com.zzhua.TestApplication: The following profiles are active: dev
if (this.logStartupInfo) {
logStartupInfo(context.getParent() == null);
logStartupProfileInfo(context);
}
// 向容器中注入指定的单例(我们拿到beanFactory也可以调用registerSingleton来直接注册单例)
// 注册springApplicationArguments、springBootBanner
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
if (printedBanner != null) {
beanFactory.registerSingleton("springBootBanner", printedBanner);
}
// 如果是DefaultListableBeanFactory,
// 使用SpringApplication的allowBeanDefinitionOverriding覆盖DefaultListableBeanFactory的DefaultListableBeanFactory属性
if (beanFactory instanceof DefaultListableBeanFactory) {
((DefaultListableBeanFactory) beanFactory)
.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
// 如果SpringApplication的lazyInitlization属性为true, 添加LazyInitializationBeanFactoryPostProcessor工厂后置处理器
// (默认不添加)
if (this.lazyInitialization) {
context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
}
// 载入所有的source, 里面包括primarySources和sources属性(可手动添加包名、类名、xml配置文件)
Set<Object> sources = getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
// 载入这些资源
load(context, sources.toArray(new Object[0]));
// 通知所有的SpringApplicationRunListener监听器, 上下文的资源已载入, 等待刷新了
listeners.contextLoaded(context);
}
public Set<Object> getAllSources() {
Set<Object> allSources = new LinkedHashSet<>();
// 默认只包含入口类(当然也可以指定多个)
if (!CollectionUtils.isEmpty(this.primarySources)) {
allSources.addAll(this.primarySources);
}
// sources是Set类型的
if (!CollectionUtils.isEmpty(this.sources)) {
allSources.addAll(this.sources);
}
// 将不可变的allSources返回
return Collections.unmodifiableSet(allSources);
}
protected void load(ApplicationContext context, Object[] sources) {
// 创建BeanDefinitionLoader,
// 传入了BeanDefinitionRegistry(context本身就是BeanDefinitionRegistry)和sources
BeanDefinitionLoader loader = createBeanDefinitionLoader(getBeanDefinitionRegistry(context), sources);
// 设置beanNameGenerator
if (this.beanNameGenerator != null) {
loader.setBeanNameGenerator(this.beanNameGenerator);
}
// 设置resourceLoader
if (this.resourceLoader != null) {
loader.setResourceLoader(this.resourceLoader);
}
// 设置environment
if (this.environment != null) {
loader.setEnvironment(this.environment);
}
// 载入
loader.load();
}
这里别落了个重点,我们进去继续看看
protected BeanDefinitionLoader createBeanDefinitionLoader(BeanDefinitionRegistry registry, Object[] sources) {
// 创建了BeanDefinitionLoader, 传入了BeanDefinitionRegistry和sources
return new BeanDefinitionLoader(registry, sources);
}
看看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;
// 注解的BeanDeifnitionReader读取器
this.annotatedReader = new AnnotatedBeanDefinitionReader(registry);
// xml配置文件的BeanDeifnitionReader读取器
this.xmlReader = new XmlBeanDefinitionReader(registry);
// 还支持groovy
if (isGroovyPresent()) {
this.groovyReader = new GroovyBeanDefinitionReader(registry);
}
// 类路径扫描器(详细扫描过程见: https://www.processon.com/view/link/620e5193f346fb61741eef93)
this.scanner = new ClassPathBeanDefinitionScanner(registry);
this.scanner.addExcludeFilter(new ClassExcludeFilter(sources));
}
留意下这个支持注解的BeanDefinitionReader
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
this(registry, getOrCreateEnvironment(registry));
}
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.notNull(environment, "Environment must not be null");
this.registry = registry;
this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
// 【关键来了: 往BeanDefinitionRegistry中注册了大量用于支持注解的BeanFactory后置处理器和Bean后置处理器】
// 比如: 特别重要的ConfigurationClassPostProcessor和AutowiredAnnotationBeanPostProcessor
// 当然还有一些,
// 如:CommonAnnotationBeanPostProcessor、
// EventListenerMethodProcessor、
// DefaultEventListenerFactory、
// PersistenceAnnotationBeanPostProcessor(根据是否能加载EntityManagerFactory类,来决定是否添加)
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
if (beanFactory != null) {
// 设置依赖比较器(比较@Order或实现Order接口的值)
if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
}
// 设置基于注解的候选bean解析器(处理@Lazy(代理)、@qualifier)
if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
}
}
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
// “org.springframework.context.annotation.internalConfigurationAnnotationProcessor”
// 这个特别重要, 专门用来解析配置的beanFactory后置处理器【ConfigurationClassPostProcessor】
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// “org.springframework.context.annotation.internalAutowiredAnnotationProcessor”
// 用来处理@Autowired注解的bean后置处理器【AutowiredAnnotationBeanPostProcessor】
if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// 如果存在javax.annotation.Resource注解的话, 并且没有“org.springframework.context.annotation.internalCommonAnnotationProcessor”
// 注册CommonAnnotationBeanPostProcessor的bean后置处理器, 用来处理@Resource和@PostConstruct和@PreDestory注解
if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// 如果存在jpa的javax.persistence.EntityManagerFactory类的话,
// 那就注册“org.springframework.context.annotation.internalPersistenceAnnotationProcessor”
// 的PersistenceAnnotationBeanPostProcessor
if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition();
try {
def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
AnnotationConfigUtils.class.getClassLoader()));
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
}
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// 注册“org.springframework.context.event.internalEventListenerProcessor”
// 的EventListenerMethodProcessor
if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
}
// 注册“org.springframework.context.event.internalEventListenerFactory”
// 的DefaultEventListenerFactory
if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
}
return beanDefs;
}
等到上面的准备工作做完了,现在就开始载入了
int load() {
int count = 0;
// 对sources挨个载入
for (Object source : this.sources) {
count += load(source);
}
return count;
}
private int load(Object source) {
Assert.notNull(source, "Source must not be null");
// 显然, 添加的primarySources是作为class载入的
if (source instanceof Class<?>) {
return load((Class<?>) source);
}
if (source instanceof Resource) {
return load((Resource) source);
}
if (source instanceof Package) {
return load((Package) source);
}
// 而且SpringApplication里的sources属性只会放入String
// 先把这个字符串当作一个配置类载入,
// 如果不是类,就当作一个Resource载入
// 如果也不是Resource,就当作一个包来扫描
// (因为前面准备工作都做好了, 所以完全具备执行上述操作的条件)
if (source instanceof CharSequence) {
return load((CharSequence) source);
}
throw new IllegalArgumentException("Invalid source type " + source.getClass());
}
刷新容器,非常重要的一步!!!
private void refreshContext(ConfigurableApplicationContext context) {
// 刷新容器(这就涉及到spring ioc的内容了)
// 而且我们要留意到, 容器的类型是上面提到过的AnnotationConfigServletWebServerApplicationContext
// 它几乎组合了spring框架和spring-web中的所有功能, 提供了很多的扩展功能
refresh(context);
if (this.registerShutdownHook) {
try {
// 注册一个JVM关闭时的勾子线程(用来关闭容器)
context.registerShutdownHook();
}
catch (AccessControlException ex) {
// Not allowed in some environments.
}
}
}
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 准备上下文刷新
// 1. 初始化propertySource
// 添加servletContextInitParams->ServletContextPropertySource(封装ServletContext)
// 添加servletConfigInitParams->ServletConfigPropertySource(封装ServletConfig)
// 2. 校验环境中必须要用的属性
prepareRefresh();
// 通知子类去刷新内部的beanFactory工厂
// AnnotationConfigServletWebServerApplicationContext作为GenericApplicationContext的子类,
// 在这一步仅仅给beanFactory设置了个serializationId
// (为什么好像啥也没干?因为前面在BeanDefinitionLoader的load方法里都干完了)
// 但如果是其它的ApplicationContext实现(比如是AbstractRefreshableApplicationContext, 它就是在这一步读取beanDefinition的)
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 准备beanFactory
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// 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();
}
}
}
准备刷新
protected void prepareRefresh() {
// 开始计时, 标记当前容器处于激活状态
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
// 模板方法,留给子类一个机会去加载属性源到env中
initPropertySources();
getEnvironment().validateRequiredProperties();
// 如果earlyApplicationListeners未初始化(还为null),
// 则初始化它,并且将之前添加到applicationListeners属性中的监听器都加到earlyApplicationListeners中去
// (之前是在EventPublishingRunListener#contextLoaded时, 获取到SpringApplication实例中的所有ApplicationListener监听器,
// 而SpringApplication实例中的所有ApplicationListener监听器,则是在SpringApplication的构造方法中, 通过SpringFactoriesLoader加载而来的)
// 如果earlyApplicationListeners已初始化, 则将原来的applicationListeners清空掉,
// 并且, 将earlyApplicationListeners添加到applicationListener中
// 通过这个if-else就保证了earlyApplicationListeners和applicationListeners中始终保持了一致
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// 初始化earlyApplicationEvents, 因为当事件多播器还未初始化时, 发布的事件将会先记录下来(添加到这个集合中)
// 等到事件多播器刚初始化好, 就立即把记录下来的事件发布出去
this.earlyApplicationEvents = new LinkedHashSet<>();
}
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 通知子类去刷新内部的beanFactory工厂
// AnnotationConfigServletWebServerApplicationContext作为GenericApplicationContext的子类,
// 在这一步仅仅给beanFactory设置了个serializationId
// (为什么好像啥也没干?因为前面在BeanDefinitionLoader的load方法里都干完了)
// 但如果是其它的ApplicationContext实现(比如是AbstractRefreshableApplicationContext, 它就是在这一步读取beanDefinition的)
// 刷新beanFactory
refreshBeanFactory();
// 获取beanFactory
return getBeanFactory();
}
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 设置类加载器
// 设置spel表达式解析器
// 添加属性编辑器注册表(用来注册属性编辑器用的)
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// ApplicationContextdAware接口会被回调, 就是因为这个bean后置处理器存在
// 还有: EnvironmentAware、EmbeddedValueResolverAware、ResourceLoaderAware、
// ApplicationEventPublisherAware、MessageSourceAware
// 也都是因为这个处理器而生效
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
// 设置忽略的依赖注入, 因为下面6个会被上面这个后置处理器处理了,不需要依赖注入再做解析了
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// 设置可解析的依赖, 凡是遇到BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext类型的依赖
// 优先注入当前的spring上下文
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// 如果单例bean实现了ApplicationListener接口, 那么会在这个bean初始化之后, 由该后置处理器添加到监听器集合当中
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// 不太清楚, 当bean实现了LoadTimeWeaverAware接口, 就从容器中拿到LoadTimeWeaver设置给该bean
// 但生效的前提是容器中要配置了名为loadTimeWeaver的bean才行,并且类型必须是LoadTimeWeaver类
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// 注册env对象到spring容器中,作为"environment"单例
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
// 注册env的systemProperties对象到spring容器中,作为"systemProperties"单例
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
// 注册env的systemEnvironment对象到spring容器中,作为"systemEnvironment"单例
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
@Override
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 注册WebApplicationContextServletContextAwareProcessor后置处理器
// 当bean实现了ServletContextAware或ServletConfigAware接口时,将对应的ServletContext或ServletConfigAware设置给bean
beanFactory.addBeanPostProcessor(new WebApplicationContextServletContextAwareProcessor(this));
// 因为 ServletContextAware已经有后置处理器处理了, 忽略该类型的依赖
beanFactory.ignoreDependencyInterface(ServletContextAware.class);
// 1. 往beanFactory中注入web应用的Scope,比如:RequestScope、SessionScope
// 这就是为什么可以写request和session在@Scope注解的原因
// 2. 往beanFactory中注入可解析的依赖,比如:RequestObjectFactory、ResponseObjectFactory、SessionObjectFactory、WebRequestObjectFactory
// 这就是为什么我们可以直接在bean中注解注入HttpServletRequest的原因(内部使用了动态代理的方式实现的)
registerWebApplicationScopes();
}
registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory,@Nullable ServletContext sc) {
beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope());
beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope());
if (sc != null) {
ServletContextScope appScope = new ServletContextScope(sc);
beanFactory.registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope);
// Register as ServletContext attribute, for ContextCleanupListener to detect it.
sc.setAttribute(ServletContextScope.class.getName(), appScope);
}
beanFactory.registerResolvableDependency(ServletRequest.class, new RequestObjectFactory());
beanFactory.registerResolvableDependency(ServletResponse.class, new ResponseObjectFactory());
beanFactory.registerResolvableDependency(HttpSession.class, new SessionObjectFactory());
beanFactory.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory());
if (jsfPresent) {
FacesDependencyRegistrar.registerFacesDependencies(beanFactory);
}
}
见PostProcessorRegistrationDelegate
// 传入了前面添加到context中的beanFactory后置处理器
// (注意, 前面在AnnotationConfigUtils#registerAnnotationConfigProcessors方法中添加的那些后置处理器啥的, 还只是BeanDefinition噢, 还没有被创建出来呢!)
// 但是仍然有些地方加了些beanFactory的后置处理器
public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// 首先, 要调用BeanDefinitionRegistryPostProcessors的后置处理器
Set<String> processedBeans = new HashSet<>();
// DefaultLitableBean实现了BeanDefinitionRegistry接口
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
// 常规的BeanFactoryPostProcessor的bean工厂后置处理器
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
// BeanDefinitionRegistryPostProcessor的beanDefinition的工后置处理器
// (BeanDefinitionRegistryPostProcessor继承了BeanFactoryPostProcessor接口)
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
// 遍历传过来的所有beanFactoryPostProcessors工厂后置处理器
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
// 如果是实现了 BeanDefinitionRegistryPostProcessor的特殊工厂后置处理器
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
// 强转
BeanDefinitionRegistryPostProcessor registryProcessor =(BeanDefinitionRegistryPostProcessor) postProcessor;
// 让BeanDefinitionRegistryPostProcessor处理这个BeanDefinitionRegistry
// 外部传入的BeanDefinitionRegistryPostProcessor具有更高的优先级处理BeanDefinitionRegistry
registryProcessor.postProcessBeanDefinitionRegistry(registry);
// 添加到 registryProcessor
registryProcessors.add(registryProcessor);
}
else {
// 如果为实现BeanDefinitionRegistryPostProcessor接口,
// 添加到常规的工厂后置处理器集合中
regularPostProcessors.add(postProcessor);
}
}
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// 首先, 找到所有实现BeanDefinitionRegistryPostProcessor接口的beanDefinition的名字
// 这里就包括了大名鼎鼎的 ConfigurationClassPostProcessor 了
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// 遍历所有的BeanDefinitionRegistryPostProcessor的beanDefinition名字
for (String ppName : postProcessorNames) {
// 先把实现了PriorityOrdered的BeanDefinitionRegistryPostProcessor先创建出来,
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 添加到currentRegistryProcessors集合中
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
// 标记该名字的后处理器已经创建
processedBeans.add(ppName);
}
}
// 对currentRegistryProcessors按Order接口值排序
// (此时还只是处理PriorityOrdered的BeanDefinitionRegistryPostProcessor)
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 将当前的currentRegistryProcessors合并到registryProcessors
registryProcessors.addAll(currentRegistryProcessors);
// 遍历currentRegistryProcessors中所有的 BeanDefinitionRegistryPostProcessor,
// 回调它们的postProcessBeanDefinitionRegistry(BeanDefinitionRegistry)方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
// 调用完currentRegistryProcessors, 就清理掉(因为前面已经添加到了registryProcessors集合中了)
currentRegistryProcessors.clear();
// 接下来, 继续获取所有实现BeanDefinitionRegistryPostProcessor接口的beanDefinition的名字(同前面)
// 但是, 为什么要重新调用一次这个方法呢? 因为上面优先的BeanDefinitionRegistryPostProcessor有可能
// 又往里面添加BeanDefinitionRegistryPostProcessor类型的的BeanDefinition了
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// 遍历它们
for (String ppName : postProcessorNames) {
// 再把实现了Ordered的BeanDefinitionRegistryPostProcessor给创建出来,
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
// 添加到currentRegistryProcessors集合中(刚刚这个集合被清空了一次)
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
// 标记该ppName已处理
processedBeans.add(ppName);
}
}
// 对currentRegistryProcessors按Order接口值排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 继续将当前的currentRegistryProcessors合并到registryProcessors
registryProcessors.addAll(currentRegistryProcessors);
// 继续遍历currentRegistryProcessors中所有的 BeanDefinitionRegistryPostProcessor,
// 回调它们的postProcessBeanDefinitionRegistry(BeanDefinitionRegistry)方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// 重复调用beanFactory获取BeanDefinitionRegistryPostProcessor的方法
// 一直到所有BeanDefinitionRegistryPostProcessor(包括处理过程中又添加进去的)都被处理完
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}
// 所有的BeanDefinitionRegistoryPostProcessor已经都调用完postPrcessBeanDefinitionRegistry()
// 先调用 registryProcessors集合中的的BeanFactoryPostProcessor的postProcessBeanFactory方法
// (非方法外部传入的, 它们具有顺序)
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
// 再调用 regularPostProcessors集合中的的BeanFactoryPostProcessor的postProcessBeanFactory方法
// (方法外部传入的)
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// 使用的DefaultListableBeanFactory实现了BeanDefinitionRegistry接口,所以不会走这里
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// 对BeanFactoryPostPrcessor再来一遍
// 找到所有实现BeanFactoryPostProcessor接口的beanDefinition的名字
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// 实现了priorityOrdered的BeanFactoryPostProcessor集合
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
// 实现了Ordered的BeanFactoryPostProcessor集合
List<String> orderedPostProcessorNames = new ArrayList<>();
//未实现Ordered的BeanFactoryPostProcessor集合
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
// 如果在processedBeans中,说明在前面已经调用过了, 不需要再调用一遍了
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
// 实现了PriorityOrdered 和 实现Ordered 和 未实现Ordered的区分开来, 添加到对应的集合里
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// 首先, 对实现了PriorityOrdered的BeanFactoryPostProcessor的排序,并调用
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 然后, 对实现了Ordered的BeanFactoryPostProcessor的排序,并调用
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// 最后, 对没有实现Ordered的BeanFactoryPostProcessor直接调用
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// 清理缓存
beanFactory.clearMetadataCache();
}
见PostProcessorRegistrationDelegate
public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
// 获取到所有实现了BeanPostProcessor接口的beanDefinition的名字
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// 添加一个BeanPostProcessorChecker的bean后置处理器
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// 实现了PriorityOrdered接口的BeanPostProcessor
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
// 实现了MergedBeanDefinitionPostProcessor接口的BeanPostProcessor
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
// 实现了Ordered接口的BeanPostProcessor的名字
List<String> orderedPostProcessorNames = new ArrayList<>();
// 未实现Ordered接口的BeanPostProcessor的名字
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
// 首先实例化实现了PriorityOrdered的BeanPostProcessor, 并添加到集合中
// 但是实现了Ordered接口和未实现Ordered接口的BeanPostProcessor, 此时并未实例化只是添加到了对应的
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// 首先, 对实现了PriorityOrdered接口的BeanPostProcessor进行排序
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 将此priorityOrderedPostProcessors添加到beanFactory中
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// 然后, 才对实现了Ordered接口的BeanPostProcessor实例化,
// 并且如果还实现了MergedBeanDefinitionPostProcessor,也添加到internalPostProcessors集合中
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
// 对实现了PriorityOrdered接口的BeanPostProcessor进行排序
sortPostProcessors(orderedPostProcessors, beanFactory);
// 将此orderedPostProcessors添加到beanFactory中
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// 最后, 对未实现Ordered接口的BeanPostProcessor进行同样的处理
// 实例化它们, 并且对实现了MergedBeanDefinitionPostProcessor添加到internalPostProcessors
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
// 直接添加到beanFactory中
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// 对internalPostProcessors排序
sortPostProcessors(internalPostProcessors, beanFactory);
// 再次将internalPostProcessors注册到beanFactory中
// (因为前面已经注册了一遍,再次注册一遍会先移除掉,再添加进去,这样顺序就跳到后面去了)
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// 继续注册ApplicationListenerDetector,把顺序调到后面了
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
初始化消息源对象
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 当前bean工厂(不包括父工厂)中,是否包含名为“messageSource”的bean
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
// 获取到 名为“messageSource”,类型为 MessageSource 的bean
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// 如果当前bean工厂的messageSource是HierarchicalMessageSource类型,
// 那就将父bean工厂中的messageSource设置给当前的messageSource
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
if (hms.getParentMessageSource() == null) {
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
}
else {
// 如果beanFactory中未定义MessageSource的bean
// 那么创建DelegatingMessageSource对象, 并将父bean工厂的messageSource设置进去
// 将刚刚创建的DelegatingMessageSource对象, 注册为单例
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource); // 注册单例
}
}
初始化应用事件多播器
protected void initApplicationEventMulticaster() {
// 获取beanFactory
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 如果当前beanFactory工厂包含名为"applicationEventMulticaster"的bean,
// 就直接使用
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
}
else {
// 如果beanFactory工厂中未定义"applicationEventMulticaster"的bean,
// 那就创建一个SimpleApplicationEventMulticaster, 并将它注册为单例
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
}
}
子类ServletWebServerApplicationContext(AnnotationConfigServletWebServerApplicationContext的父类),有重写onRefresh这个方法
@Override
protected void onRefresh() {
// 父类GenericApplicationContext初始化ThemeSource
super.onRefresh();
try {
// 创建WebServer服务器
createWebServer();
}
catch (Throwable ex) {
throw new ApplicationContextException("Unable to start web server", ex);
}
}
创建WebServer服务器
private void createWebServer() {
WebServer webServer = this.webServer;
ServletContext servletContext = getServletContext();
if (webServer == null && servletContext == null) {
// 创建一个ServletWebServerFactory的工厂,这个工厂将用于创建WebServer实例
// 在sprngboot有个自动配置类, ServletWebServerFactoryAutoConfiguration,里面引入了3种
// TomcatServletWebServerFactory、
// JettyServletWebServerFactory、
// UndertowServletWebServerFactory、
// 它们将根据条件决定生效(只能有一个生效,否则报错)
ServletWebServerFactory factory = getWebServerFactory();
// 使用ServletWebServerFactory的工厂, 创建WebServer服务器, 来统一不同web服务器的行为(比如后面web容器的启动)
// 获取容器中所有的 ServletContextInitializer 接口的bean
// 这个接口有如下的子类实现, 它们将用于初始化ServletContext
// (其实就是往ServletContext中添加过滤器、servlet、监听器这web中的三大组件)
// ServletRegistrationBean、
// FilterRegistrationBean
// DelegatingFilterProxyRegistrationBean
// ServletListenerRegistrationBean
// 当然我们也可以自己实现ServletContextInitializer接口,来往ServletContext中添加组件或者是其它扩展
// 这也是为什么我们在springboot要添加过滤器时,
// 只需要定义FilterRegistrationBean类型的bean, 就可以添加进去了
// 除此之外, 我们可以直接定义Servlet、Filter、
// ServletContextAttributeListener、
// ServletRequestListener、
// ServletRequestAttributeListener
// HttpSessionAttributeListener、
// HttpSessionListener、
// ServletContextListener
// 这些类型的bean, 也可以实现往ServletContext中添加对应的组件,springboot会适配它们
// 但是请注意, 在这里ServletContext在此时还并未创建, 现在只是在收集ServletContextInitializer的bean
// 以便于后面web容器在启动时, 往servletContext添加web组件
// 以tomcatcat为例, 这些bean都封装在TomcatStarter中, 而TomcatStarter实现了ServletContainerInitializer接口
// (这的确很像Servlet 3.0之动态注册组件的规范,但却不是通过SPI加载的ServletContainerInitializer接口的实现的,
// 而是以编码的方式实现的, 注意哦web应用启动后,就不能再往web容器中添加组件了!
// 现在springboot相当于将tomcat的加载、启动过程也纳入到springboot的启动流程中了,
// 那么自然而然就可以在web容器启动加载的时候, 往里面添加组件了)
// 当然现在tomcat服务器还没启动, 只是在准备一些必要的初始化器
// 详细过程: SpringBoot内置Web容器加载原理及web组件注册https://www.processon.com/view/link/61f265aee0b34d06c3b5cb53、
this.webServer = factory.getWebServer(getSelfInitializer());
}
else if (servletContext != null) {
try {
getSelfInitializer().onStartup(servletContext);
}
catch (ServletException ex) {
throw new ApplicationContextException("Cannot initialize servlet context", ex);
}
}
initPropertySources();
}
注册应用监听器
protected void registerListeners() {
// 获取到springboot添加的监听器(通过SpringFactoriesLoader加载的)
// 将它们注册到事件多播器中
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// 获取到容器中定义的ApplicationListener监听器
// 将它们注册到事件多播器中
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// 从prepareRefresh开始到当前的过程中,发布的事件都会先记录在earlyApplicationEvents属性中
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
// 将earlyApplicationEvents置为null
// (可以结合AbstractApplicationContext#publishEvent方法,
// 里面判断如果earlyApplicationEvents为nul就直接发布了,
// 不为null就保存到earlyApplicationEvents属性中)
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
在这一步将完成beanFactory工厂的初始化
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// 获取容器中名为conversionService的bean,
// 如果它是ConversionService类型,则把它设置给beanFactory作为类型转换服务
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME)
&& beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
// 注册值解析器, 使用env用来解析配置值
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// 触发LoadTimeWeaverAware类型的bean的getBean
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
beanFactory.setTempClassLoader(null);
beanFactory.freezeConfiguration();
// 预实实例化单例(非懒加载)的bean,到了spring创建bean的环节了(非常重要!!!)
beanFactory.preInstantiateSingletons();
}
完成beanFactory工厂的刷新,而ServletWebServerApplicationContext刚好重写了这个方法
@Override
protected void finishRefresh() {
// 调用父类完成刷新的方法
super.finishRefresh();
// 在此处才开始启动web容器
WebServer webServer = startWebServer();
// 容器启动成功后,发布ServletWebServerInitializedEvent事件
if (webServer != null) {
publishEvent(new ServletWebServerInitializedEvent(webServer, this));
}
}
再看看父类的finishRefresh
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
clearResourceCaches();
// 初始化LifecycleProcessor
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
getLifecycleProcessor().onRefresh();
// 使用当前this,发布容器刷新完了的事件
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);
}
初始化生命周期处理器,它和 Lifecycle、SmartLifecycle、LifecycleProcessor相关,详细流程,可以参考:Lifecycle&SmartLifecycle&LifecycleProcessor生命周期
protected void initLifecycleProcessor() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 如果容器中定义了名为“lifecycleProcessor”的bean,
// 那就获取到它, 设置给lifecycleProcessor属性
if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
this.lifecycleProcessor = beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
}
else {
// 如果容器中,没有定义名为“lifecycleProcessor”的bean,
// 那就创建1个 DefaultLifecycleProcessor ,并将它注册为单例
DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
// 保存beanFactory到DefaultLifecycleProcessor 对象中
defaultProcessor.setBeanFactory(beanFactory);
this.lifecycleProcessor = defaultProcessor;
beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
}
}
空方法
void started(ConfigurableApplicationContext context) {
// 回调所有 SpringApplicationRunListener 的started方法
for (SpringApplicationRunListener listener : this.listeners) {
listener.started(context);
}
}
private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList<>();
// 获取 ApplicationRunner 类型的bean
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
// 获取 CommandLineRunner 类型的bean
runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
// 对这些runner一起排序
AnnotationAwareOrderComparator.sort(runners);
// 按顺序回调它们的run方法, 它们的传参不一样,
// ApplicationRunner传的是最开始的ApplicationArguments
// CommandLineRunner传的是ApplicationArguments#getSourceArgs
for (Object runner : new LinkedHashSet<>(runners)) {
if (runner instanceof ApplicationRunner) {
callRunner((ApplicationRunner) runner, args);
}
if (runner instanceof CommandLineRunner) {
callRunner((CommandLineRunner) runner, args);
}
}
}
void running(ConfigurableApplicationContext context) {
// 回调所有 SpringApplicationRunListener 的running方法
for (SpringApplicationRunListener listener : this.listeners) {
listener.running(context);
}
}