<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
复制代码
启动一个springBoot程序(Servlet环境):java
@Slf4j
@EnableDiscoveryClient
@SpringBootApplication
public class KeplerPostLoanApplication {
/** * 项目启动类 * * @param args 启动参数 */
public static void main(String[] args) {
SpringApplication.run(KeplerPostLoanApplication.class, args)
}
}
复制代码
调用SpringApplication.run方法web
public static ConfigurableApplicationContext run(Class<?>[] primarySources,
String[] args) {
return new SpringApplication(primarySources).run(args);
}
复制代码
先执行SpringApplication的构造方法,进行初始化动做,包括:spring
public SpringApplication(Class<?>... primarySources) {
this(null, primarySources);
}
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
this.webApplicationType = WebApplicationType.deduceFromClasspath();
// 加载META-INF/spring.factories文件中,定义的ApplicationContextInitializer
setInitializers((Collection)getSpringFactoriesInstances(
ApplicationContextInitializer.class));
// 加载META-INF/spring.factories文件中,定义的ApplicationListener
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}
复制代码
接下来看一下run作了什么bootstrap
/** * Run the Spring application, creating and refreshing a new * {@link ApplicationContext}. * @param args the application arguments (usually passed from a Java main method) * @return a running {@link ApplicationContext} */
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
// 获取SpringApplicationRunListener
// 默认只有EventPublishingRunListener,用来结合spring启动流程,发布SpringApplicationEvent
SpringApplicationRunListeners listeners = getRunListeners(args);
// 发布ApplicationStartingEvent,例如
// ApplicationPidFileWriter(saves application PID into file)
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
//建立容器环境
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
// 建立容器上下文
context = createApplicationContext();
exceptionReporters = getSpringFactoriesInstances(
SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
// 准备上下文
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
// 刷新上下文
refreshContext(context);
// 子类扩展
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
// 发布ApplicationStartedEvent
listeners.started(context);
// 回调ApplicationRunner、CommandLineRunner
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;
}
复制代码
概括下SpringApplication.run方法的关键动做设计模式
其中:执行过程当中,经过SpringApplicationRunListener的实现类EventPublishingRunListener在对应动做的时间点,Spring启动事件。tomcat
附上,springApplicationEvent事件列表bash
/** SpringApplication.java **/
private ConfigurableEnvironment prepareEnvironment( SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) {
// 一、初始化environment
ConfigurableEnvironment environment = getOrCreateEnvironment();
// 二、加载默认配置,defaultProperties、springApplicationCommandLineArgs
configureEnvironment(environment, applicationArguments.getSourceArgs());
// 3.发布ApplicationEnvironmentPreparedEvent,例如
// (若是是spring Cloud环境的话)BootstrapApplicationListener,建立bootstrapContext上下文,加载bootstrap.properties,
// 补充下,BootstrapApplicationListener会初始化Spring Cloud上下文,初始化过程当中,同样会调用SpringApplication.run方法(即当前方法)
// ConfigFileApplicationListener,加载application的YamlProperty文件与PropertiesProperty文件,添加PropertySourceOrderingPostProcessor
// 补充下,有须要扩展,须要注意优先级,保证是否定期望的在bootstrap.properties、application.properties加载前或者加载后
listeners.environmentPrepared(environment);
bindToSpringApplication(environment);
if (!this.isCustomEnvironment) {
environment = new EnvironmentConverter(getClassLoader())
.convertEnvironmentIfNecessary(environment, deduceEnvironmentClass());
}
ConfigurationPropertySources.attach(environment);
return environment;
}
复制代码
首先getOrCreateEnvironment方法实现以下: new 一个StandardXXXEnvironment(),其中,构造函数中会执行customizePropertySources方法,加载基础的的PropertySource(系统变量、环境变量、web变量)app
private ConfigurableEnvironment getOrCreateEnvironment() {
if (this.environment != null) {
return this.environment;
}
switch (this.webApplicationType) {
case SERVLET:
return new StandardServletEnvironment();
case REACTIVE:
return new StandardReactiveWebEnvironment();
default:
return new StandardEnvironment();
}
}
public AbstractEnvironment() {
customizePropertySources(this.propertySources);
}
复制代码
附上StandardEnvironment的customizePropertySources实现less
@Override
protected void customizePropertySources(MutablePropertySources propertySources) {
// 属性获取时,for each propertySources,先匹配到就返回,
// 因此systemProperties(如:java -Dsource=xxx -jar xxx.jar)优先级高于systemEnvironment(环境变量)
propertySources.addLast(new MapPropertySource("systemProperties", getSystemProperties()));
propertySources.addLast(new SystemEnvironmentPropertySource("systemEnvironment", getSystemEnvironment()));
}
复制代码
实际上,就是new AnnotationConfigServletWebServerApplicationContext()dom
// SpringApplication.java
protected ConfigurableApplicationContext createApplicationContext() {
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
switch (this.webApplicationType) {
case SERVLET:
contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
break;
case REACTIVE:
contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
break;
default:
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);
}
复制代码
重点关注:构造方法中, 建立了AnnotatedBeanDefinitionReader、ClassPathBeanDefinitionScanner两个对象
// AnnotationConfigServletWebServerApplicationContext.java
public AnnotationConfigServletWebServerApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
复制代码
其中,AnnotatedBeanDefinitionReader 建立过程当中,注册了多个十分重要的BeanPostProcessor,包括处理@Configuration注解的ConfigurationClassPostProcessor等。
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);
// Register all relevant annotation post processors in the given registry,包括:
// ConfigurationClassPostProcessor
// AutowiredAnnotationBeanPostProcessor
// RequiredAnnotationBeanPostProcessor
// CommonAnnotationBeanPostProcessor
// PersistenceAnnotationBeanPostProcessor
// EventListenerMethodProcessor
// DefaultEventListenerFactory
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
复制代码
/** SpringApplication.java **/
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
context.setEnvironment(environment);
postProcessApplicationContext(context);
// 调用ApplicationContextInitializer.initialize(),例如:
// EnvironmentDecryptApplicationInitializer
// PropertySourceBootstrapConfiguration
applyInitializers(context);
// ApplicationContextInitializedEvent,暂无例子
listeners.contextPrepared(context);
if (this.logStartupInfo) {
logStartupInfo(context.getParent() == null);
logStartupProfileInfo(context);
}
// Add boot specific singleton beans
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
if (printedBanner != null) {
beanFactory.registerSingleton("springBootBanner", printedBanner);
}
if (beanFactory instanceof DefaultListableBeanFactory) {
((DefaultListableBeanFactory) beanFactory)
.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
// Load the sources
Set<Object> sources = getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
// 加载springBoot启动类注入到spring容器中bean map中
// AnnotatedBeanDefinitionReader.doRegisterBean()
load(context, sources.toArray(new Object[0]));
// 发布ApplicationPreparedEvent
// ConfigFileApplicationListener,注入PropertySourceOrderingPostProcessor,调整defaultProperties到尾部
listeners.contextLoaded(context);
}
复制代码
refresh方法在spring整个源码体系中举足轻重,后续单独讲解。
private void refreshContext(ConfigurableApplicationContext context) {
refresh(context);
if (this.registerShutdownHook) {
try {
context.registerShutdownHook();
}
catch (AccessControlException ex) {
// Not allowed in some environments.
}
}
}
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
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 afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) {
}
复制代码
扩展接口,设计模式中的模板方法,默认为空实现,子类扩展。
容器就绪后,触发回调动做,目前见到的实现有 JobLauncherCommandLineRunner,启动jobLauncher
private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList<>();
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
AnnotationAwareOrderComparator.sort(runners);
for (Object runner : new LinkedHashSet<>(runners)) {
if (runner instanceof ApplicationRunner) {
callRunner((ApplicationRunner) runner, args);
}
if (runner instanceof CommandLineRunner) {
callRunner((CommandLineRunner) runner, args);
}
}
}
复制代码