文章目录
启动
SpringApplication是springBoot appilication的入口函数,一般通过SpringApplication.run启动一个boot application。
demo1
@Configuration
@EnableAutoConfiguration
public class MyApplication {
// ... Bean definitions
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
demo2:
public static void main(String[] args) {
SpringApplication application = new SpringApplication(MyApplication.class);
// ... customize application settings here
application.run(args)
}
kotlin demo
package com.example.demo
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class DemoApplication
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
runApplication只是一个helper函数
package org.springframework.boot
import org.springframework.context.ConfigurableApplicationContext
/**
* Top level function acting as a Kotlin shortcut allowing to write
* `runApplication<FooApplication>(arg1, arg2)` instead of
* `SpringApplication.run(FooApplication::class.java, arg1, arg2)`.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
inline fun <reified T : Any> runApplication(vararg args: String): ConfigurableApplicationContext =
SpringApplication.run(T::class.java, *args)
/**
* Top level function acting as a Kotlin shortcut allowing to write
* `runApplication<FooApplication>(arg1, arg2) { // SpringApplication customization ... }`
* instead of instantiating `SpringApplication` class, customize it and then invoking
* `run(arg1, arg2)`.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
inline fun <reified T : Any> runApplication(vararg args: String, init: SpringApplication.() -> Unit): ConfigurableApplicationContext =
SpringApplication(T::class.java).apply(init).run(*args)
主要功能
Create an appropriate ApplicationContext instance (depending on your classpath)
见org.springframework.boot.ApplicationContextFactory#DEFAULT
web:AnnotationConfigServletWebServerApplicationContext
reactive: AnnotationConfigReactiveWebServerApplicationContext
none: AnnotationConfigApplicationContext
Register a CommandLinePropertySource to expose command line arguments as Spring properties
CommandLineProperty会被加入到所有property的最后面,也就是拥有最高优先级。另外Environment也是这时候创建的
Refresh the application context, loading all singleton beans
就是调用一个ApplicationContext.refresh
Trigger any CommandLineRunner beans
CommandLineRunner 也是在这儿被调用的
Function details
static run helpers
两个重载形式的static helper
/**
* Static helper that can be used to run a {@link SpringApplication} from the
* specified source using default settings.
* @param primarySource the primary source to load
* @param args the application arguments (usually passed from a Java main method)
* @return the running {@link ApplicationContext}
*/
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
return run(new Class<?>[] { primarySource }, args);
}
/**
* Static helper that can be used to run a {@link SpringApplication} from the
* specified sources using default settings and user supplied arguments.
* @param primarySources the primary sources to load
* @param args the application arguments (usually passed from a Java main method)
* @return the running {@link ApplicationContext}
*/
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return new SpringApplication(primarySources).run(args);
}
可以看到都是实例化一个SpringApplication然后调用run函数,所以我们当然也可以自己实例化一个SpringApplication然后调用run函数
constructor
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();
this.bootstrapRegistryInitializers = new ArrayList<>(
getSpringFactoriesInstances(BootstrapRegistryInitializer.class));
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}
resourceLoader 通常是null,我们没有定制化这个的需求。如果需要加载特殊的class,可能需要定制化这个
primarySources: 通常我们就一个main class,可以在这里加上,也可以设置resources字段,是我们的SpringApplication从多个地方加载类。比如我们有个第三方package需要扫描发现component,就可以这么干。具体的说明:
* {@link SpringApplication}s can read beans from a variety of different sources. It is
* generally recommended that a single {@code @Configuration} class is used to bootstrap
* your application, however, you may also set {@link #getSources() sources} from:
* <ul>
* <li>The fully qualified class name to be loaded by
* {@link AnnotatedBeanDefinitionReader}</li>
* <li>The location of an XML resource to be loaded by {@link XmlBeanDefinitionReader}, or
* a groovy script to be loaded by {@link GroovyBeanDefinitionReader}</li>
* <li>The name of a package to be scanned by {@link ClassPathBeanDefinitionScanner}</li>
* </ul>
webApplicationType :
public enum WebApplicationType {
/**
* The application should not run as a web application and should not start an
* embedded web server.
*/
NONE,
/**
* The application should run as a servlet-based web application and should start an
* embedded servlet web server.
*/
SERVLET,
/**
* The application should run as a reactive web application and should start an
* embedded reactive web server.
*/
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";
static WebApplicationType deduceFromClasspath() {
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;
}
}
return WebApplicationType.SERVLET;
}
}
通常就是SERVLET,在特殊环境比如test,backfill,我们可以手动设置 spring.main.web-application-type=none.
稍后我们可以看到spring.main.*是如何被绑定到 SpringApplication的属性上的。
bootstrapRegistryInitializers: 这个通常是空的
setInitializers: spring-boot.jar: spring.factories
# Application Context Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
org.springframework.boot.context.ContextIdApplicationContextInitializer,\
org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\
org.springframework.boot.rsocket.context.RSocketPortInfoApplicationContextInitializer,\
org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer
listeners: spring-boot.jar: spring.factories
# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.context.FileEncodingApplicationListener,\
org.springframework.boot.context.config.AnsiOutputApplicationListener,\
org.springframework.boot.context.config.DelegatingApplicationListener,\
org.springframework.boot.context.logging.LoggingApplicationListener,\
org.springframework.boot.env.EnvironmentPostProcessorApplicationListener
mainApplicationClass: 就是我们的main class
private Class<?> deduceMainApplicationClass() {
try {
StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
if ("main".equals(stackTraceElement.getMethodName())) {
return Class.forName(stackTraceElement.getClassName());
}
}
}
catch (ClassNotFoundException ex) {
// Swallow and continue
}
return null;
}
RuntimeException在初始化的时候会生成stacktrace,这算不算一个hack的用法呢?java.lang.Thread#getStackTrace貌似更合适一些,但是
public StackTraceElement[] getStackTrace() {
if (this != Thread.currentThread()) {
// check for getStackTrace permission
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(
SecurityConstants.GET_STACK_TRACE_PERMISSION);
}
// optimization so we do not call into the vm for threads that
// have not yet started or have terminated
if (!isAlive()) {
return EMPTY_STACK_TRACE;
}
StackTraceElement[][] stackTraceArray = dumpThreads(new Thread[] {this});
StackTraceElement[] stackTrace = stackTraceArray[0];
// a thread that was alive during the previous isAlive call may have
// since terminated, therefore not having a stacktrace.
if (stackTrace == null) {
stackTrace = EMPTY_STACK_TRACE;
}
return stackTrace;
} else {
return (new Exception()).getStackTrace();
}
}
居然也是通过exception来获取stacktrace的,确实是涨姿势了。getStackTrace不应该被Exception调用的吗?怎么反了?
run
public ConfigurableApplicationContext run(String... args) {
long startTime = System.nanoTime();
DefaultBootstrapContext bootstrapContext = createBootstrapContext();
ConfigurableApplicationContext context = null;
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting(bootstrapContext, this.mainApplicationClass);
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
context.setApplicationStartup(this.applicationStartup);
prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
refreshContext(context);
afterRefresh(context, applicationArguments);
Duration timeTakenToStartup = Duration.ofNanos(System.nanoTime() - startTime);
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), timeTakenToStartup);
}
listeners.started(context, timeTakenToStartup);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, listeners);
throw new IllegalStateException(ex);
}
try {
Duration timeTakenToReady = Duration.ofNanos(System.nanoTime() - startTime);
listeners.ready(context, timeTakenToReady);
}
catch (Throwable ex) {
handleRunFailure(context, ex, null);
throw new IllegalStateException(ex);
}
return context;
}
bootstrapContext:
private DefaultBootstrapContext createBootstrapContext() {
DefaultBootstrapContext bootstrapContext = new DefaultBootstrapContext();
this.bootstrapRegistryInitializers.forEach((initializer) -> initializer.initialize(bootstrapContext));
return bootstrapContext;
}
上面分析了bootstrapRegistryInitializers是空的,所以就没用到,这个bootstrapContext只会在SpringApplication初始化阶段用到,貌似用处不大,SpringApplication才用处多。第三方可以把它加在spring.factory里面实现定制化SpringApplication等骚操作。
这个DefaultBootstrapContext很简单,只是用于在bootstrap阶段完成(SpringApplication开始初始化之前)发送一个BootstrapContextClosedEvent,关心这个事件的话可以调用addCloseListener注册
configureHeadlessProperty:
private boolean headless = true;
private void configureHeadlessProperty() {
System.setProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS,
System.getProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, Boolean.toString(this.headless)));
}
这块是用来设置java.awt.headless属性为true还是false。
java.awt.headless是J2SE的一种模式,用于在缺失显示屏、鼠标或者键盘时的系统配置。对于后端服务来讲,很多都是需要将这个属性设置为true的。
不知道干啥的,awt图形相关的都没用到
listeners:
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting(bootstrapContext, this.mainApplicationClass);
这个是SpringApplicationRunListener不是constructor里面的SpringApplication.listeners,那个是ApplicationListener,接收SpringApplication的整个寿命周期事件,比如parentContext refreshed等等,而SpringApplicationRunListener只会在SpringApplication初始化的时候被回调,也就是当前的Run函数。这个局部变量在run完成后就丢失了。
environment:
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
DefaultBootstrapContext bootstrapContext, ApplicationArguments applicationArguments) {
// Create and configure the environment
ConfigurableEnvironment environment = getOrCreateEnvironment();
configureEnvironment(environment, applicationArguments.getSourceArgs());
ConfigurationPropertySources.attach(environment);
listeners.environmentPrepared(bootstrapContext, environment);
DefaultPropertiesPropertySource.moveToEnd(environment);
Assert.state(!environment.containsProperty("spring.main.environment-prefix"),
"Environment prefix cannot be set via properties.");
bindToSpringApplication(environment);
if (!this.isCustomEnvironment) {
EnvironmentConverter environmentConverter = new EnvironmentConverter(getClassLoader());
environment = environmentConverter.convertEnvironmentIfNecessary(environment, deduceEnvironmentClass());
}
ConfigurationPropertySources.attach(environment);
return environment;
}
有两个需要注意的地方
1, configureEnvironment
protected void configureEnvironment(ConfigurableEnvironment environment, String[] args) {
if (this.addConversionService) {
environment.setConversionService(new ApplicationConversionService());
}
configurePropertySources(environment, args);
configureProfiles(environment, args);
}
添加了profile和source
2, bindToSpringApplication
protected void bindToSpringApplication(ConfigurableEnvironment environment) {
try {
Binder.get(environment).bind("spring.main", Bindable.ofInstance(this));
}
catch (Exception ex) {
throw new IllegalStateException("Cannot bind to SpringApplication", ex);
}
}
这就是为啥spring.main.*相当于设置SpringApplication的属性
为什么ConfigurationPropertySources.attach调用了两次?
第一次ConfigurationPropertySources.attach, 发送listeners.environmentPrepared, DefaultPropertiesPropertySource.moveToEnd, 然后bindToSpringApplication,convertEnvironmentIfNecessary这时候转换完成,再次ConfigurationPropertySources.attach
environment 主要是加载数据源,解析数据,设置ovverride的逻辑等,这部分可以略过。
configureIgnoreBeanInfo:
这个是javaBeans相关的,略过
createApplicationContext:这个是重头戏
ApplicationContextFactory DEFAULT = (webApplicationType) -> {
try {
for (ApplicationContextFactory candidate : SpringFactoriesLoader
.loadFactories(ApplicationContextFactory.class, ApplicationContextFactory.class.getClassLoader())) {
ConfigurableApplicationContext context = candidate.create(webApplicationType);
if (context != null) {
return context;
}
}
return new AnnotationConfigApplicationContext();
}
catch (Exception ex) {
throw new IllegalStateException("Unable create a default ApplicationContext instance, "
+ "you may need a custom ApplicationContextFactory", ex);
}
};
可以看到是从spring.factories里面加载的,在spring-boot.jat/meta-info.spring.factories里面
# Application Context Factories
org.springframework.boot.ApplicationContextFactory=\
org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext.Factory,\
org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext.Factory
所以会分别调用AnnotationConfigReactiveWebServerApplicationContext.Factory, AnnotationConfigServletWebServerApplicationContext.Factory。 最终的结果就是AnnotationConfigReactiveWebServerApplicationContext,或者AnnotationConfigServletWebServerApplicationContext,或者AnnotationConfigApplicationContext
prepareContext:
private void prepareContext(DefaultBootstrapContext bootstrapContext, ConfigurableApplicationContext context,
ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments, Banner printedBanner) {
context.setEnvironment(environment);
postProcessApplicationContext(context);
applyInitializers(context);
listeners.contextPrepared(context);
bootstrapContext.close(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 AbstractAutowireCapableBeanFactory) {
((AbstractAutowireCapableBeanFactory) beanFactory).setAllowCircularReferences(this.allowCircularReferences);
if (beanFactory instanceof DefaultListableBeanFactory) {
((DefaultListableBeanFactory) beanFactory)
.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
}
if (this.lazyInitialization) {
context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
}
context.addBeanFactoryPostProcessor(new PropertySourceOrderingBeanFactoryPostProcessor(context));
// Load the sources
Set<Object> sources = getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
load(context, sources.toArray(new Object[0]));
listeners.contextLoaded(context);
}
1, 设置环境抽象,主要是需要用到很多配置文件
2, postProcessApplicationContext, beanNameGenerator 和resourceLoader 都是null,但是conversionService是设置了。注意BeanFactory的BeanPostProcessor不是在这儿调用的。
protected void postProcessApplicationContext(ConfigurableApplicationContext context) {
if (this.beanNameGenerator != null) {
context.getBeanFactory().registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR,
this.beanNameGenerator);
}
if (this.resourceLoader != null) {
if (context instanceof GenericApplicationContext) {
((GenericApplicationContext) context).setResourceLoader(this.resourceLoader);
}
if (context instanceof DefaultResourceLoader) {
((DefaultResourceLoader) context).setClassLoader(this.resourceLoader.getClassLoader());
}
}
if (this.addConversionService) {
context.getBeanFactory().setConversionService(context.getEnvironment().getConversionService());
}
}
3, 调用ApplicationInilializer。
比如DelegatingApplicationContextInitializer, 他会调用环境变量里边指定的context.initializer.classes
public void initialize(ConfigurableApplicationContext context) {
ConfigurableEnvironment environment = context.getEnvironment();
List<Class<?>> initializerClasses = getInitializerClasses(environment);
if (!initializerClasses.isEmpty()) {
applyInitializerClasses(context, initializerClasses);
}
}
这样我们就可以把initializer写在配置文件里面了
4, 发送contextPrepared消息
5, 关闭bootstrapContext,发送BootstrapContextClosedEvent
6, logStartupInfo包括spring基本信息以及实用的profile
7, 添加springApplicationArguments, springBootBanner, 所以在自己的bean里面可以autowire这两个bean
8,加载并注册source指定的beans,通常只是我们的main class
/**
* Load beans into the application context.
* @param context the context to load beans into
* @param sources the sources to load
*/
protected void load(ApplicationContext context, Object[] sources) {
if (logger.isDebugEnabled()) {
logger.debug("Loading source " + StringUtils.arrayToCommaDelimitedString(sources));
}
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();
}
BeanDefinitionLoader(BeanDefinitionRegistry registry, Object... sources) {
Assert.notNull(registry, "Registry must not be null");
Assert.notEmpty(sources, "Sources must not be empty");
this.sources = sources;
this.annotatedReader = new AnnotatedBeanDefinitionReader(registry);
this.xmlReader = (XML_ENABLED ? new XmlBeanDefinitionReader(registry) : null);
this.groovyReader = (isGroovyPresent() ? new GroovyBeanDefinitionReader(registry) : null);
this.scanner = new ClassPathBeanDefinitionScanner(registry);
this.scanner.addExcludeFilter(new ClassExcludeFilter(sources));
}
void load() {
for (Object source : this.sources) {
load(source);
}
}
private void load(Object source) {
Assert.notNull(source, "Source must not be null");
if (source instanceof Class<?>) {
load((Class<?>) source);
return;
}
if (source instanceof Resource) {
load((Resource) source);
return;
}
if (source instanceof Package) {
load((Package) source);
return;
}
if (source instanceof CharSequence) {
load((CharSequence) source);
return;
}
throw new IllegalArgumentException("Invalid source type " + source.getClass());
}
所以springboot可以通过指定source属性来添加各种形式的bean定义。AnnotatedBeanDefinitionReader。
再仔细查看loader的细节。对于大多数只有一个main class的boot程序,其实只是通过AnnotatedBeanDefinitionReader注册了primarySource(main class)这一个bean。这个也是非常合理的,因为componentScan和AutoConfiguration都是要读取这个main class bean以后才进行的,所以当前就只注册了这一个bean。
9,发送contextLoaded事件
refreshContext:
private void refreshContext(ConfigurableApplicationContext context) {
if (this.registerShutdownHook) {
shutdownHook.registerApplicationContext(context);
}
refresh(context);
}
shutdownHook在jvm关闭的时候调用ConfigurableApplicationContext #close。Refresh的逻辑主要委托给context。
注意,ApplicationContext这个类只是注册了primarySource这一个BeanDefinition,剩下的bean扫描需要context自己去完成。
afterRefresh: 是一个空函数,我们可以继承ApplicationContext并实现这个函数。基本没用吧。怎么不跟其他一样使用spring.fatories的类或者Listener呢?
listeners.started --> callRunners --> listeners.ready
所以事件的顺序是ApplicationStarted --> runner run --> ApplicationReady
很多内置服务比如http都是在refreshContext的时候初始化环境,在收到ApplicationReady的时候正在监听端口并服务。
总结
SpringApplication只是在正在的ApplicationContext启动之前做一些环境准备的引导工作。并且只在ApplicationContext里面注册了一个primary source的BeanDefinition,真正的扫描加载bean以及apply beanPostProcessor等工作还是ApplicationContext自己去完成的。