Springboot2.0的启动详解
简单介绍
0.先来说说启动类的注解
1 | @SpringBootApplication |
其中,类注解@SpringBootApplication
的实现为
1 | @Target(ElementType.TYPE) |
其中,@SpringBootConfiguration
,@EnableAutoConfiguration
和@ComponentScan
为主要注解,用这三个注解代替启动类上的@SpringBootApplication
也能使工程正常运行。
详解@SpringBootConfiguration,@EnableAutoConfiguration和@ComponentScan
三个注解主要做一件事:注册bean到spring容器,通过不同条件不同方式来完成。
- @SpringBootConfiguration
其底层为1
2
3
4
5
6
7@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
}
1 |
|
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
// 主要注解,通过导入方式,将制定class注册到Spring容器
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
}
1
2
3
4
5
6
7
```@EnableAutoConfiguration```从classpath中搜索所有的```META-INF/spring.factories```配置文件,将```org.springframework.boot.autoconfigure.EnableutoConfiguration```对应的配置项通过反射实例化为对应标注了```@Configuartion```的JavaConfig形式的IoC容器配置类,汇总成一个,加载到IoC容器。
* 组件扫描 @ComponentScan
注解源码
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan {
// 对应的包扫描路径
@AliasFor("basePackages")
String[] value() default {};
// 对应的包扫描路径
@AliasFor("value")
String[] basePackages() default {};
// 指定具体扫描类
Class<?>[] basePackageClasses() default {};
// 对应bean名称生成器,默认BeanNameGenerator.class
Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;
// 对应监测到的bean的scope范围
Class<? extends ScopeMetadataResolver> scopeResolver() default AnnotationScopeMetadataResolver.class;
// 为监测到的组件生成代理
ScopedProxyMode scopedProxy() default ScopedProxyMode.DEFAULT;
// 控制符合组件检测条件的类文件,默认在包扫描下
String resourcePattern() default ClassPathScanningCandidateComponentProvider.DEFAULT_RESOURCE_PATTERN;
// 是否对带@Component,@Repository,@Service,@Controller自动检测,默认开启
boolean useDefaultFilters() default true;
// 指定定义Filter满足条件的组件
Filter[] includeFilters() default {};
// 排除定义Filter不满足条件的组件
Filter[] excludeFilters() default {};
// 扫描到的类进行懒加载,默认关闭
boolean lazyInit() default false;
}
1
2
3
4
5
6
7
8
```@ComponentScan```该注解告知Spring要扫描那些类或包,默认扫描该注解所在包及子包下所有类。
所以在SpringBoot项目中,启动类放在顶层目录中,以便扫描到所有类。
扫描特定注解注释的类,将其注册到Spring容器中。
### 1.由如下代码启动
在这个main方法中,调用了SpringApplication的静态run方法,并将Application类对象和main方法的参数args作为参数传递了进去。
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
1 | ### 2.在这个静态方法中,创建SpringApplication对象,并调用该对象的run方法。 |
public static ConfigurableApplicationContext run(Class<?> primarySource, String… args) {
return run(new Class[]{primarySource}, args);
}
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return (new SpringApplication(primarySources)).run(args);
}
1 | ### 3.进入SpringApplication类中看到 |
/**
* Create a new {@link SpringApplication} instance. The application context will load
* beans from the specified primary sources (see {@link SpringApplication class-level}
* documentation for details. The instance can be customized before calling
*/
public SpringApplication(Class<?>... primarySources) {
this(null, primarySources);
}
/**
* Create a new {@link SpringApplication} instance. The application context will load
* beans from the specified primary sources (see {@link SpringApplication class-level}
* documentation for details. The instance can be customized before calling
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
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 = deduceWebApplicationType();
setInitializers((Collection) getSpringFactoriesInstances(
ApplicationContextInitializer.class));
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}
1 |
|
/**
* The class name of application context that will be used by default for reactive web
* environments.
*/
public static final String DEFAULT_REACTIVE_WEB_CONTEXT_CLASS = "org.springframework."
+ "boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext";
private static final String REACTIVE_WEB_ENVIRONMENT_CLASS = "org.springframework."
+ "web.reactive.DispatcherHandler";
private static final String MVC_WEB_ENVIRONMENT_CLASS = "org.springframework."
+ "web.servlet.DispatcherServlet";
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
...
this.webApplicationType = deduceWebApplicationType();
...
}
1 |
|
private WebApplicationType deduceWebApplicationType() {
// 响应式web应用
if (ClassUtils.isPresent(REACTIVE_WEB_ENVIRONMENT_CLASS, null)
&& !ClassUtils.isPresent(MVC_WEB_ENVIRONMENT_CLASS, null)) {
return WebApplicationType.REACTIVE;
}
for (String className : WEB_ENVIRONMENT_CLASSES) {
// 不是web应用
if (!ClassUtils.isPresent(className, null)) {
return WebApplicationType.NONE;
}
}
// 基于servlet的web应用
return WebApplicationType.SERVLET;
}
1 |
|
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
...
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
...
}
/**
* Sets the {@link ApplicationContextInitializer} that will be applied to the Spring
*/
public void setInitializers(
Collection<? extends ApplicationContextInitializer<?>> initializers) {
this.initializers = new ArrayList<>();
this.initializers.addAll(initializers);
}
1 |
|
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
return getSpringFactoriesInstances(type, new Class<?>[] {});
}
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type,
Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// 使用名字保证唯一性,避免重复冲突
Set<String> names = new LinkedHashSet<>(
SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
1 |
public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
String factoryClassName = factoryClass.getName();
return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader);
if (result != null) {
return result;
} else {
try {
Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
LinkedMultiValueMap result = new LinkedMultiValueMap();
while(urls.hasMoreElements()) {
URL url = (URL)urls.nextElement();
UrlResource resource = new UrlResource(url);
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
Iterator var6 = properties.entrySet().iterator();
while(var6.hasNext()) {
Entry<?, ?> entry = (Entry)var6.next();
List<String> factoryClassNames = Arrays.asList(StringUtils.commaDelimitedListToStringArray((String)entry.getValue()));
result.addAll((String)entry.getKey(), factoryClassNames);
}
}
cache.put(classLoader, result);
return result;
} catch (IOException var9) {
throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var9);
}
}
}
1 |
|
Enumeration
1 |
|
Application Context Initializers
初始化ApplicationContext,在refresh前调用
org.springframework.context.ApplicationContextInitializer=\
为ApplicationContext添加检查配置,并在常见错误配置时打印警告信息BeanFactoryPostProcessor
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
为ApplicationContext设置id
org.springframework.boot.context.ContextIdApplicationContextInitializer,\
从ApplicationContext环境配置中读取Initializer并应用
org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\
为ApplicationContext设置环境变量,以便单元测试中使用服务器正监听的端口号
org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer
1 |
|
private <T> List<T> createSpringFactoriesInstances(Class<T> type,
Class<?>[] parameterTypes, ClassLoader classLoader, Object[] args,
Set<String> names) {
List<T> instances = new ArrayList<>(names.size());
for (String name : names) {
try {
Class<?> instanceClass = ClassUtils.forName(name, classLoader);
Assert.isAssignable(type, instanceClass);
Constructor<?> constructor = instanceClass
.getDeclaredConstructor(parameterTypes);
T instance = (T) BeanUtils.instantiateClass(constructor, args);
instances.add(instance);
}
catch (Throwable ex) {
throw new IllegalArgumentException(
"Cannot instantiate " + type + " : " + name, ex);
}
}
return instances;
}
1 |
|
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
...
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
...
}
/**
* Sets the {@link ApplicationListener}s that will be applied to the SpringApplication
* and registered with the {@link ApplicationContext}. */
public void setListeners(Collection<? extends ApplicationListener<?>> listeners) {
this.listeners = new ArrayList<>();
this.listeners.addAll(listeners);
}
1 |
|
Application Listeners
观察者模式的监听器接口,监听各种ApplicationEvent
org.springframework.context.ApplicationListener=\
清缓存
org.springframework.boot.ClearCachesApplicationListener,\
父context关闭,关闭当前ApplicationContext
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
当系统属性System.encoding与配置的spring编码不同时,打印错误信息,并终止系统启动
org.springframework.boot.context.FileEncodingApplicationListener,\
根据属性spring.output.ansi.enabled配置ANSI输出(彩色输出日志)
org.springframework.boot.context.config.AnsiOutputApplicationListener,\
搜索加载配置文件,并根据配置文件设置Environment与Application
org.springframework.boot.context.config.ConfigFileApplicationListener,\
加载并转发事件至context.listener.classes中配置的ApplicationLIstener
org.springframework.boot.context.config.DelegatingApplicationListener,\
程序正常启动成功:将classpath打印至debug日志
程序正常启动失败:将classpath打印至info日志
org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,\
根据配置,适当的时候初始化与配置日志系统
org.springframework.boot.context.logging.LoggingApplicationListener,\
若classpath中存在类liquibase.servicelocator.ServiceLocator,替换成适用于springboot的版本
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener
1 |
|
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
...
this.mainApplicationClass = deduceMainApplicationClass();
}
private Class<?> deduceMainApplicationClass() {
try {
StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
// 获取当前调用栈
if ("main".equals(stackTraceElement.getMethodName())) {
// 找到main方法所在类并返回
return Class.forName(stackTraceElement.getClassName());
}
}
}
catch (ClassNotFoundException ex) {
// Swallow and continue
}
return null;
}
1 | ### 4.SpringApplication对象的run方法 |
public static ConfigurableApplicationContext run(Class<?>[] primarySources,
String[] args) {
return new SpringApplication(primarySources).run(args);
}
public ConfigurableApplicationContext run(String... args) {
// StopWatch是来自org.springframework.util的工具类,可以用来方便的记录程序的运行时间
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
// 设置headless模式
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
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);
}
listeners.started(context);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, listeners, exceptionReporters, ex);
throw new IllegalStateException(ex);
}
listeners.running(context);
return context;
}
1 |
|
private static final String SYSTEM_PROPERTY_JAVA_AWT_HEADLESS = "java.awt.headless";
private boolean headless = true;
public ConfigurableApplicationContext run(String... args) {
...
// 设置headless模式
configureHeadlessProperty();
...
}
private void configureHeadlessProperty() {
System.setProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, System.getProperty(
SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, Boolean.toString(this.headless)));
}
1 |
|
Run Listeners
org.springframework.boot.SpringApplicationRunListener=\
RunListener是在SpringApplication对象的run方法执行到不同的阶段时,发布相应的event给SpringApplication对象的成员变量listeners中记录的事件监听器。
org.springframework.boot.context.event.EventPublishingRunListener
1 |
public ConfigurableApplicationContext run(String... args) {
...
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
// 把main函数的args参数当做一个PropertySource来解析
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
// 配置环境:读取执行配置文件:profiles与properties
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
// 跳过特定Bean的配置
configureIgnoreBeanInfo(environment);
// banner打印
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);
}
listeners.started(context);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, listeners, exceptionReporters, ex);
throw new IllegalStateException(ex);
}
listeners.running(context);
return context;
}
private SpringApplicationRunListeners getRunListeners(String[] args) {
Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
return new SpringApplicationRunListeners(logger, getSpringFactoriesInstances(
SpringApplicationRunListener.class, types, this, args));
}
```
Tips:Environment代表着程序运行的环境,主要包含了两种信息
- profiles,用来描述哪些bean definitions是可用的
- properties,用来描述系统的配置,其来源可能是配置文件、JVM属性文件、操作系统环境变量等等