Springboot简介
相信大多数开发者对Springboot比较熟悉了,它能够快速地创建一个spring应用,能够完全摒弃XML的配置方式,并且内嵌了Tomcat、Jetty这样的Servlet容器,即无需再将应用打包成war部署。
在Springboot之前,部署一个应用如下
而现在,由于Springboot内嵌了Servlet容器,于是可以将应用打包成jar,直接运行一个jar包就能启动一个web服务。
Springboot是如何做到的呢?接下来进入今天的正题
Tomcat-embed
Springboot能够将Tomcat内嵌,是因为Tomcat提供了一套JavaAPI,能够通过Tomcat tomcat = new Tomcat()
来创建一个Tomcat容器。
只需要引入Maven依赖
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>${tomcat.version}</version>
</dependency>
接下来我们通过Springboot源码来看看,spring是如何使用这套API与自身结合的
Springboot源码解读
首先,任意一个Springboot应用,都有一个main()
函数作为应用的启动方法,里面调用了SpringApplication.run(MyApplication.class, args)
,我们就从这个run()
开始,解密spring容器如何启动Tomcat。
这个run()
的实现代码如下,这里去掉了一些与主线逻辑无关的代码
/**
* Run the Spring application, creating and refreshing a new
* {@linkApplicationContext}.
* @param args the application arguments (usually passed from a Java main method)
* @return a running {@link ApplicationContext}
*/
public ConfigurableApplicationContext run(String... args) {
ConfigurableApplicationContext context = null;
// 创建spring容器对象 ApplicationContext
context = createApplicationContext();
// 做一些初始化容器之前的预备操作
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// 启动spring容器核心方法,包括启动tomcat
refreshContext(context);
// 做一些容器启动之后的操作(当前这个方法是空的)
afterRefresh(context, applicationArguments);
return context;
}
看过Spring源码的同学应该清楚,启动spring容器的核心方法就是refresh()
,而这里的方法名叫refreshContext(context)
,不过是springboot对refresh()
的封装罢了,所以内部依然是调用的refresh()
,于是我们来到这个核心方法内部
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 在容器启动之前做一些准备操作
prepareRefresh();
// 通知子类去刷新实例工厂
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 初始化当前容器中的实例工厂
prepareBeanFactory(beanFactory);
try {
// 允许容器中的基类对实例工厂进行后置处理
postProcessBeanFactory(beanFactory);
// 调用实例工厂中的后置处理器
invokeBeanFactoryPostProcessors(beanFactory);
// 注册实例的后置处理器,在创建实例时进行拦截
registerBeanPostProcessors(beanFactory);
// 初始化消息资源
initMessageSource();
// 初始化容器中的事件处理器
initApplicationEventMulticaster();
// 初始化一些在特定容器中特殊的实例