public static void main(String[] args) {
//xxx.class:主配置类,(能够传多个)
SpringApplication.run(xxx.class, args);
}
/**
* ConfigurableApplicationContext(可配置的应用程序上下文)
*/
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
//调用下面的run方法
return run(new Class[]{primarySource}, args);
}
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
//primarySources:主配置类
return (new SpringApplication(primarySources)).run(args);
}
public SpringApplication(Class<?>... primarySources) {
//调用下面构造方法
this((ResourceLoader) 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));
//获取当前应用的类型,是否是web应用,见2.1
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//从类路径下找到META‐INF/spring.factories配置的全部ApplicationContextInitializer;而后保存起来,见2.2
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
//从类路径下找到META‐INF/spring.factories配置的全部spring.ApplicationListener;而后保存起来,原理同上
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
//从多个SpringApplication中找到有main方法的主SpringApplication(在调run方法的时候是能够传递多个配置类的)
//只记录有main方法的类名,以便下一步的run
this.mainApplicationClass = deduceMainApplicationClass();
}
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;
}
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = getClassLoader();
// Use names and ensure unique to protect against duplicates
// 配置的全部ApplicationContextInitializer等分别到一个集合中以便查询使用,其中loadFactoryNames方法从类路径下找到META‐INF/spring.factories中传入的parameterTypes
Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
// 实例化传入的类
List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
// 排序以便提升针对他执行操做的效率
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
private Class<?> deduceMainApplicationClass() {
try {
// 查询当前的虚拟机的当前线程的StackTrace信息
StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
// 查看当前线程中已加载的类中有没有main方法
if ("main".equals(stackTraceElement.getMethodName())) {
//有则返回该类的类名
return Class.forName(stackTraceElement.getClassName());
}
}
}
catch (ClassNotFoundException ex) {
// Swallow and continue
}
return null;
}
StackTrace简述react
1 StackTrace用栈的形式保存了方法的调用信息.web
2 怎么获取这些调用信息呢?spring
可用Thread.currentThread().getStackTrace()方法获得当前线程的StackTrace信息.该方法返回的是一个StackTraceElement数组.数据库
3 该StackTraceElement数组就是StackTrace中的内容.数组
4 遍历该StackTraceElement数组.就能够看到方法间的调用流程.springboot
好比线程中methodA调用了methodB那么methodA先入栈methodB再入栈.服务器
5 在StackTraceElement数组下标为2的元素中保存了当前方法的所属文件名,当前方法所属的类名,以及该方法的名字app
除此之外还能够获取方法调用的行数.less
6 在StackTraceElement数组下标为3的元素中保存了当前方法的调用者的信息和它调用时的代码行数.ide
public ConfigurableApplicationContext run(String... args) {
//Simple stop watch, allowing for timing of a number of tasks, exposing totalrunning time and running time for each named task.简单来讲是建立ioc容器的计时器
StopWatch stopWatch = new StopWatch();
stopWatch.start();
//声明IOC容器
ConfigurableApplicationContext context = null;
//异常报告存储列表
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
//加载图形化配置
this.configureHeadlessProperty();
//从类路径下META‐INF/spring.factories获取SpringApplicationRunListeners,原理同2中获取ApplicationContextInitializer和ApplicationListener
SpringApplicationRunListeners listeners = this.getRunListeners(args);
//遍历上一步获取的全部SpringApplicationRunListener,调用其starting方法
listeners.starting();
Collection exceptionReporters;
try {
//封装命令行
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
//准备环境,把上面获取到的SpringApplicationRunListeners传过去,见3.1
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
this.configureIgnoreBeanInfo(environment);
//打印Banner,就是控制台那个Spring字符画
Banner printedBanner = this.printBanner(environment);
//根据当前环境利用反射建立IOC容器,见3.2
context = this.createApplicationContext();
//从类路径下META‐INF/spring.factories获取SpringBootExceptionReporter,原理同2中获取ApplicationContextInitializer和ApplicationListener
exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
//准备IOC容器,见3.3
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
//刷新IOC容器,可查看配置嵌入式Servlet容器原理,全部的@Configuration和@AutoConfigutation等Bean对象全在此时加入容器中,并依据不一样的选项建立了不一样功能如服务器/数据库等组件。见3.4
//能够说@SpringbootApplication中自动扫描包和Autoconfiguration也是在此时进行的
this.refreshContext(context);
//这是一个空方法
this.afterRefresh(context, applicationArguments);
//中止计时,打印时间
stopWatch.stop();
if (this.logStartupInfo) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
}
//调用全部SpringApplicationRunListener的started方法
listeners.started(context);
//见3.5 ,从ioc容器中获取全部的ApplicationRunner和CommandLineRunner进行回调ApplicationRunner先回调,CommandLineRunner再回调。
this.callRunners(context, applicationArguments);
} catch (Throwable var10) {
this.handleRunFailure(context, var10, exceptionReporters, listeners);
throw new IllegalStateException(var10);
}
try {
//调用全部SpringApplicationRunListener的running方法
listeners.running(context);
//返回建立好的ioc容器,启动完成
return context;
} catch (Throwable var9) {
this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
throw new IllegalStateException(var9);
}
}
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) {
//获取或者建立环境,有则获取,无则建立
ConfigurableEnvironment environment = this.getOrCreateEnvironment();
//配置环境
this.configureEnvironment((ConfigurableEnvironment)environment, applicationArguments.getSourceArgs());
ConfigurationPropertySources.attach((Environment)environment);
//建立环境完成后,ApplicationContext建立前,调用前面获取的全部SpringApplicationRunListener的environmentPrepared方法,读取配置文件使之生效
listeners.environmentPrepared((ConfigurableEnvironment)environment);
// 环境搭建好后,需依据他改变Apllication的参数,将enviroment的信息放置到Binder中,再由Binder依据不一样的条件将“spring.main”SpringApplication更改成不一样的环境,为后面context的建立搭建环境
//为何boot要这样作,其实我们启动一个boot的时候并非必定只有一个Application且用main方式启动。这样子咱们能够读取souces配置多的Application
this.bindToSpringApplication((ConfigurableEnvironment)environment);
if (!this.isCustomEnvironment) {
environment = (new EnvironmentConverter(this.getClassLoader())).convertEnvironmentIfNecessary((ConfigurableEnvironment)environment, this.deduceEnvironmentClass());
}
ConfigurationPropertySources.attach((Environment)environment);
//回到3,将建立好的environment返回
return (ConfigurableEnvironment)environment;
}
protected ConfigurableApplicationContext createApplicationContext() {
//获取当前Application中ioc容器类
Class<?> contextClass = this.applicationContextClass;
//若没有则依据该应用是否为web应用而建立相应的ioc容器
//除非为其传入applicationContext,否则Application的默认构造方法并不会建立ioc容器
if (contextClass == null) {
try {
switch(this.webApplicationType) {
case SERVLET:
contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext");
break;
case REACTIVE:
contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext");
break;
default:
contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext");
}
} catch (ClassNotFoundException var3) {
throw new IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3);
}
}
//用bean工具类实例化ioc容器对象并返回。回到3
return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass);
}
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
//将建立好的环境放到IOC容器中
context.setEnvironment(environment);
//处理一些组件,没有实现postProcessA接口
this.postProcessApplicationContext(context);
//获取全部的ApplicationContextInitializer调用其initialize方法,这些ApplicationContextInitializer就是在2步骤中获取的,见3.3.1
this.applyInitializers(context);
//回调全部的SpringApplicationRunListener的contextPrepared方法,这些SpringApplicationRunListeners是在步骤3中获取的
listeners.contextPrepared(context);
//打印日志
if (this.logStartupInfo) {
this.logStartupInfo(context.getParent() == null);
this.logStartupProfileInfo(context);
}
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
//将一些applicationArguments注册成容器工厂中的单例对象
beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
if (printedBanner != null) {
beanFactory.registerSingleton("springBootBanner", printedBanner);
}
if (beanFactory instanceof DefaultListableBeanFactory) {
((DefaultListableBeanFactory)beanFactory).setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
//如果延迟加载,则在ioc容器中加入LazyInitializationBeanFactoryPostProcessor,
if (this.lazyInitialization) {
context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
}
//获取全部报告primarySources在内的全部source
Set<Object> sources = this.getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
//加载容器
this.load(context, sources.toArray(new Object[0]));
//回调全部的SpringApplicationRunListener的contextLoaded方法
listeners.contextLoaded(context);
}
protected void applyInitializers(ConfigurableApplicationContext context) {
Iterator var2 = this.getInitializers().iterator();
while(var2.hasNext()) {
//将以前的全部的ApplicationContextInitializer遍历
ApplicationContextInitializer initializer = (ApplicationContextInitializer)var2.next();
//解析查看以前从spring.factories调用的ApplicationContextInitializer是否能被ioc容器调用
Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(), ApplicationContextInitializer.class);
Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
//能够调用则对ioc容器进行初始化(还没加载咱们本身配置的bean和AutoConfiguration那些)
initializer.initialize(context);
}
}//返回3.3
@Override
//详情见内置Servlet的启动原理,最后是用ApplicationContext的实现类的refresh()方法,如果web Application则为ServletWebServerApplicationContext
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();
}
}
}
private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList();
//将ioc容器中的的ApplicationRunner和CommandLineRunner(),在建立ioc容器时建立的
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
AnnotationAwareOrderComparator.sort(runners);
Iterator var4 = (new LinkedHashSet(runners)).iterator();
//调用ApplicationRunner和CommandLineRunner的run方法
while(var4.hasNext()) {
Object runner = var4.next();
if (runner instanceof ApplicationRunner) {
this.callRunner((ApplicationRunner)runner, args);
}
if (runner instanceof CommandLineRunner) {
this.callRunner((CommandLineRunner)runner, args);
}
}
}
配置在META-INF/spring.factories
ApplicationContextInitializer(在咱们将enviroment绑定到application后能够用来建立不一样类型的context)
SpringApplicationRunListener(在Application 建立/运行/销毁等进行一些咱们想要的特殊配置)
只须要放在ioc容器中
ApplicationRunner(加载没有在ApplicationContext中的bean时让bean能加载)
CommandLineRunner(命令行执行器)
1.建立ApplicationContextInitializer和SpringApplicationRunListener的实现类,并在META-INF/spring.factories文件中配置
public class TestApplicationContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
System.out.println("TestApplicationContextInitializer.initialize");
}
}
public class TestSpringApplicationRunListener implements SpringApplicationRunListener {
@Override
public void starting() {
System.out.println("TestSpringApplicationRunListener.starting");
}
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
System.out.println("TestSpringApplicationRunListener.environmentPrepared");
}
@Override
public void contextPrepared(ConfigurableApplicationContext context) {
System.out.println("TestSpringApplicationRunListener.contextPrepared");
}
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
System.out.println("TestSpringApplicationRunListener.contextLoaded");
}
@Override
public void started(ConfigurableApplicationContext context) {
System.out.println("TestSpringApplicationRunListener.started");
}
@Override
public void running(ConfigurableApplicationContext context) {
System.out.println("TestSpringApplicationRunListener.running");
}
@Override
public void failed(ConfigurableApplicationContext context, Throwable exception) {
System.out.println("TestSpringApplicationRunListener.failed");
}
}
org.springframework.context.ApplicationContextInitializer=\
cn.clboy.springbootprocess.init.TestApplicationContextInitializer
org.springframework.boot.SpringApplicationRunListener=\
cn.clboy.springbootprocess.init.TestSpringApplicationRunListener
启动报错:说是没有找到带org.springframework.boot.SpringApplication和String数组类型参数的构造器,给TestSpringApplicationRunListener添加这样的构造器
public TestSpringApplicationRunListener(SpringApplication application,String[] args) {
}
2.建立ApplicationRunner实现类和CommandLineRunner实现类,由于是从ioc容器完成建立后中提取存放在里面的这两个Runner,所以能够直接添加到容器中,最后callRunner使用
@Component
public class TestApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("TestApplicationRunner.run\t--->"+args);
}
}
@Componentpublic class TestCommandLineRunn implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("TestCommandLineRunn.runt\t--->"+ Arrays.toString(args)); }}