目录:Springboot源码学习目录上文:07、SpringBoot 启动 创建应用上下文前言:
一、准备应用上下文
private void prepareContext(DefaultBootstrapContext bootstrapContext, ConfigurableApplicationContext context,
ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments, Banner printedBanner) {
// 将之前解析完成的环境,加入到上下文中
context.setEnvironment(environment);
// 将 SpringApplication 中的一些属性,添加到 上下文的工厂中
postProcessApplicationContext(context);
// 回调 SpringApplication 创建时,实例化的 应用上下文初始化后增强器 ApplicationContextInitializer,
applyInitializers(context);
// 发送上下文准备完成事件
listeners.contextPrepared(context);
// 后续引导上文的工作完成,发送关闭引导上下文事件,但是引导上下文创建时里面的广播器没有监听器,因此不会有任何监听器回调
bootstrapContext.close(context);
if (this.logStartupInfo) {
logStartupInfo(context.getParent() == null);
logStartupProfileInfo(context);
}
// Add boot specific singleton beans
// 获取bean工厂
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
// 以名字为springApplicationArguments,将启动参数对象添加到beanFactory
beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
if (printedBanner != null) {
// 以名字为springBootBanner,将启动参数对象添加到beanFactory
beanFactory.registerSingleton("springBootBanner", printedBanner);
}
if (beanFactory instanceof DefaultListableBeanFactory) {
// 如果当前beanFactory是DefaultListableBeanFactory类型,则设置属性,允许beanDefinition覆盖
((DefaultListableBeanFactory) beanFactory)
.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
if (this.lazyInitialization) {
// 如果当前SpringApplication 允许懒加载,则想上下文加入LazyInitializationBeanFactoryPostProcessor
context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
}
// Load the sources
Set<Object> sources = getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
// 里面过程很复杂,先创建了BeanDefinitionLoader,然后BeanDefinitionLoader中初始化了各种读取器和扫描器,但最终只做了一件事,把当前这个主启动类变成一个bean,加入到spring上下文中
load(context, sources.toArray(new Object[0]));
// 发送上下文已加载完成事件
listeners.contextLoaded(context);
}