简单的springboot项目启动代码
通过下面的代码,可以启动一个springboot项目
@SpringBootApplication
public class Bootstrap {
private static final Logger logger = LoggerFactory.getLogger(Bootstrap.class);
public static void main(String[] args) {
SpringApplication.run(Bootstrap.class, args);
}
}
main方法中,只有一行代码。下面深入来看这行代码做了哪些事情
SpringApplication
来看下它的这个静态方法的实现,最终还是调用了SpringApplication的实例的run方法来完成了项目的启动。
/**
* Static helper that can be used to run a {@link SpringApplication} from the
* specified source using default settings.
* @param source the source to load
* @param args the application arguments (usually passed from a Java main method)
* @return the running {@link ApplicationContext}
*/
public static ConfigurableApplicationContext run(Object source, String... args) {
return run(new Object[] { source }, args);
}
/**
* Static helper that can be used to run a {@link SpringApplication} from the
* specified sources using default settings and user supplied arguments.
* @param sources the sources to load
* @param args the application arguments (usually passed from a Java main method)
* @return the running {@link ApplicationContext}
*/
public static ConfigurableApplicationContext run(Object[] sources, String[] args) {
return new SpringApplication(sources).run(args);
}
SpringApplication构造函数
在构造SpringApplication实例的过程中,Springboot处理了如下几件事情,先上代码:
public SpringApplication(ResourceLoader resourceLoader, Object... sources) {
this.resourceLoader = resourceLoader;
initialize(sources);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void initialize(Object[] sources) {
if (sources != null && sources.length > 0) {
this.sources.addAll(Arrays.asList(sources));
}
// 是否是web环境
this.webEnvironment = deduceWebEnvironment();
// 设置初始化器
setInitializers((Collection) getSpringFactoriesInstances(
ApplicationContextInitializer.class));
// 设置监听器
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
// 设置有启动入口的Class类型
this.mainApplicationClass = deduceMainApplicationClass();
}
设置初始化器的步骤是遍历classpath下的所有的 META-INF/spring.factories 文件,查找key为org.springframework.context.ApplicationContextInitializer定义的所有类。有关 ApplicationContextInitializer的作用,可以参考下https://www.jianshu.com/p/3828e93be20d这边文章。
内存中调试得到的结果为:
设置监听器的方式和设置初始化器的方式一致,也是遍历classpath下的所有的 META-INF/spring.factories 文件,不过它是查找key为org.springframework.context.ApplicationListener定义的所有类。
内存中得到的调试结果为:
当上述步骤搞定后,SpringApplication的实例就创建出来了。下一步是调用其实例的run方法。
SpringAppliation#run(String... args)
先看看该方法的代码:
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
FailureAnalyzers analyzers = null;
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
analyzers = new FailureAnalyzers(context);
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
refreshContext(context);
afterRefresh(context, applicationArguments);
listeners.finished(context, null);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
return context;
}
catch (Throwable ex) {
handleRunFailure(context, listeners, analyzers, ex);
throw new IllegalStateException(ex);
}
}
configureHeadlessProperty
可以看看 java.awt.headless 详解
getRunListeners
和上面获取初始化器以及应用监听器的逻辑一样,不过这里是用来获取配置中key为org.springframework.boot.SpringApplicationRunListener的所有类。
prepareEnvironment
private ConfigurableEnvironment prepareEnvironment(
SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments) {
// Create and configure the environment
// 返回Environment对象,如果是web环境下的话,则返回StandardServletEnvironment,否则返回StandardEnvironment。
ConfigurableEnvironment environment = getOrCreateEnvironment();
// 对environment做一些配置文件和profile相关的配置
configureEnvironment(environment, applicationArguments.getSourceArgs());
listeners.environmentPrepared(environment);
if (!this.webEnvironment) {
environment = new EnvironmentConverter(getClassLoader())
.convertToStandardEnvironmentIfNecessary(environment);
}
return environment;
}
printBanner
打印欢迎语
createApplicationContext
根据环境(web or 其他)来创建不同的context
protected ConfigurableApplicationContext createApplicationContext() {
Class> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
contextClass = Class.forName(this.webEnvironment
? DEFAULT_WEB_CONTEXT_CLASS : DEFAULT_CONTEXT_CLASS);
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Unable create a default ApplicationContext, "
+ "please specify an ApplicationContextClass",
ex);
}
}
return (ConfigurableApplicationContext) BeanUtils.instantiate(contextClass);
}
后续的过程就是spring容器开始初始化的过程,在后续的文章中我会详细的来讲解。