SpringBoot的兩種啟動方式原理,你學會了嗎?
使用內(nèi)置tomcat啟動
配置案例
啟動方式
- IDEA中main函數(shù)啟動
- mvn springboot-run
- java -jar XXX.jar 使用這種方式時,為保證服務(wù)在后臺運行,會使用nohup
nohup java -jar -Xms128m -Xmx128m -Xss256k -XX:+PrintGCDetails -XX:+PrintHeapAtGC -Xloggc:/data/log/web-gc.log web.jar >/data/log/web.log &
使用java -jar默認情況下,不會啟動任何嵌入式Application Server,該命令只是啟動一個執(zhí)行jar main的JVM進程,當spring-boot-starter-web包含嵌入式tomcat服務(wù)器依賴項時,執(zhí)行java -jar則會啟動Application Server
配置內(nèi)置tomcat屬性
關(guān)于Tomcat的屬性都在 org.springframework.boot.autoconfigure.web.ServerProperties 配置類中做了定義,我們只需在application.properties配置屬性做配置即可。通用的Servlet容器配置都以 server 作為前綴
#配置程序端口,默認為8080
server.port= 8080
#用戶會話session過期時間,以秒為單位
server.session.timeout=
#配置默認訪問路徑,默認為/
server.context-path=
而Tomcat特有配置都以 server.tomcat 作為前綴
# 配置Tomcat編碼,默認為UTF-8
server.tomcat.uri-encoding=UTF-8
# 配置最大線程數(shù)
server.tomcat.max-threads=1000
注意:使用內(nèi)置tomcat不需要有tomcat-embed-jasper和spring-boot-starter-tomcat依賴,因為在spring-boot-starter-web依賴中已經(jīng)集成了tomcat
原理
從main函數(shù)說起
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
return run(new Class[]{primarySource}, args);
}
// 這里run方法返回的是ConfigurableApplicationContext
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return (new SpringApplication(primarySources)).run(args);
}
public ConfigurableApplicationContext run(String... args) {
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
this.configureHeadlessProperty();
SpringApplicationRunListeners listeners = this.getRunListeners(args);
listeners.starting();
Collection exceptionReporters;
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
this.configureIgnoreBeanInfo(environment);
//打印banner,這里可以自己涂鴉一下,換成自己項目的logo
Banner printedBanner = this.printBanner(environment);
//創(chuàng)建應(yīng)用上下文
context = this.createApplicationContext();
exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
//預(yù)處理上下文
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
//刷新上下文
this.refreshContext(context);
//再刷新上下文
this.afterRefresh(context, applicationArguments);
listeners.started(context);
this.callRunners(context, applicationArguments);
} catch (Throwable var10) {
}
try {
listeners.running(context);
return context;
} catch (Throwable var9) {
}
}
既然我們想知道tomcat在SpringBoot中是怎么啟動的,那么run方法中,重點關(guān)注創(chuàng)建應(yīng)用上下文(createApplicationContext)和刷新上下文(refreshContext)。
創(chuàng)建上下文
//創(chuàng)建上下文
protected ConfigurableApplicationContext createApplicationContext() {
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
switch(this.webApplicationType) {
case SERVLET:
//創(chuàng)建AnnotationConfigServletWebServerApplicationContext
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) {
thrownew IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3);
}
}
return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass);
}
這里會創(chuàng)建AnnotationConfigServletWebServerApplicationContext類。而AnnotationConfigServletWebServerApplicationContext類繼承了ServletWebServerApplicationContext,而這個類是最終集成了AbstractApplicationContext。
刷新上下文
//SpringApplication.java
//刷新上下文
private void refreshContext(ConfigurableApplicationContext context) {
this.refresh(context);
if (this.registerShutdownHook) {
try {
context.registerShutdownHook();
} catch (AccessControlException var3) {
}
}
}
//這里直接調(diào)用最終父類AbstractApplicationContext.refresh()方法
protected void refresh(ApplicationContext applicationContext) {
((AbstractApplicationContext)applicationContext).refresh();
}
//AbstractApplicationContext.java
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
this.postProcessBeanFactory(beanFactory);
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
this.initMessageSource();
this.initApplicationEventMulticaster();
//調(diào)用各個子類的onRefresh()方法,也就說這里要回到子類:ServletWebServerApplicationContext,調(diào)用該類的onRefresh()方法
this.onRefresh();
this.registerListeners();
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
} catch (BeansException var9) {
this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}
}
}
//ServletWebServerApplicationContext.java
//在這個方法里看到了熟悉的面孔,this.createWebServer,神秘的面紗就要揭開了。
protected void onRefresh() {
super.onRefresh();
try {
this.createWebServer();
} catch (Throwable var2) {
}
}
//ServletWebServerApplicationContext.java
//這里是創(chuàng)建webServer,但是還沒有啟動tomcat,這里是通過ServletWebServerFactory創(chuàng)建,那么接著看下ServletWebServerFactory
private void createWebServer() {
WebServer webServer = this.webServer;
ServletContext servletContext = this.getServletContext();
if (webServer == null && servletContext == null) {
ServletWebServerFactory factory = this.getWebServerFactory();
this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});
} elseif (servletContext != null) {
try {
this.getSelfInitializer().onStartup(servletContext);
} catch (ServletException var4) {
}
}
this.initPropertySources();
}
//接口
publicinterface ServletWebServerFactory {
WebServer getWebServer(ServletContextInitializer... initializers);
}
//實現(xiàn)
AbstractServletWebServerFactory
JettyServletWebServerFactory
TomcatServletWebServerFactory
UndertowServletWebServerFactory
這里ServletWebServerFactory接口有4個實現(xiàn)類,對應(yīng)著四種容器:
而其中我們常用的有兩個:TomcatServletWebServerFactory和JettyServletWebServerFactory。
//TomcatServletWebServerFactory.java
//這里我們使用的tomcat,所以我們查看TomcatServletWebServerFactory。到這里總算是看到了tomcat的蹤跡。
@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
Tomcat tomcat = new Tomcat();
File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");
tomcat.setBaseDir(baseDir.getAbsolutePath());
//創(chuàng)建Connector對象
Connector connector = new Connector(this.protocol);
tomcat.getService().addConnector(connector);
customizeConnector(connector);
tomcat.setConnector(connector);
tomcat.getHost().setAutoDeploy(false);
configureEngine(tomcat.getEngine());
for (Connector additionalConnector : this.additionalTomcatConnectors) {
tomcat.getService().addConnector(additionalConnector);
}
prepareContext(tomcat.getHost(), initializers);
return getTomcatWebServer(tomcat);
}
protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
returnnew TomcatWebServer(tomcat, getPort() >= 0);
}
//Tomcat.java
//返回Engine容器,看到這里,如果熟悉tomcat源碼的話,對engine不會感到陌生。
public Engine getEngine() {
Service service = getServer().findServices()[0];
if (service.getContainer() != null) {
return service.getContainer();
}
Engine engine = new StandardEngine();
engine.setName( "Tomcat" );
engine.setDefaultHost(hostname);
engine.setRealm(createDefaultRealm());
service.setContainer(engine);
return engine;
}
//Engine是最高級別容器,Host是Engine的子容器,Context是Host的子容器,Wrapper是Context的子容器
getWebServer這個方法創(chuàng)建了Tomcat對象,并且做了兩件重要的事情:把Connector對象添加到tomcat中,configureEngine(tomcat.getEngine());
getWebServer方法返回的是TomcatWebServer。
//TomcatWebServer.java
//這里調(diào)用構(gòu)造函數(shù)實例化TomcatWebServer
public TomcatWebServer(Tomcat tomcat, boolean autoStart) {
Assert.notNull(tomcat, "Tomcat Server must not be null");
this.tomcat = tomcat;
this.autoStart = autoStart;
initialize();
}
private void initialize() throws WebServerException {
//在控制臺會看到這句日志
logger.info("Tomcat initialized with port(s): " + getPortsDescription(false));
synchronized (this.monitor) {
try {
addInstanceIdToEngineName();
Context context = findContext();
context.addLifecycleListener((event) -> {
if (context.equals(event.getSource()) && Lifecycle.START_EVENT.equals(event.getType())) {
removeServiceConnectors();
}
});
//===啟動tomcat服務(wù)===
this.tomcat.start();
rethrowDeferredStartupExceptions();
try {
ContextBindings.bindClassLoader(context, context.getNamingToken(), getClass().getClassLoader());
}
catch (NamingException ex) {
}
//開啟阻塞非守護進程
startDaemonAwaitThread();
}
catch (Exception ex) {
stopSilently();
destroySilently();
thrownew WebServerException("Unable to start embedded Tomcat", ex);
}
}
}
//Tomcat.java
public void start() throws LifecycleException {
getServer();
server.start();
}
//這里server.start又會回到TomcatWebServer的
public void stop() throws LifecycleException {
getServer();
server.stop();
}
//TomcatWebServer.java
//啟動tomcat服務(wù)
@Override
public void start() throws WebServerException {
synchronized (this.monitor) {
if (this.started) {
return;
}
try {
addPreviouslyRemovedConnectors();
Connector connector = this.tomcat.getConnector();
if (connector != null && this.autoStart) {
performDeferredLoadOnStartup();
}
checkThatConnectorsHaveStarted();
this.started = true;
//在控制臺打印這句日志,如果在yml設(shè)置了上下文,這里會打印
logger.info("Tomcat started on port(s): " + getPortsDescription(true) + " with context path '"
+ getContextPath() + "'");
}
catch (ConnectorStartFailedException ex) {
stopSilently();
throw ex;
}
catch (Exception ex) {
thrownew WebServerException("Unable to start embedded Tomcat server", ex);
}
finally {
Context context = findContext();
ContextBindings.unbindClassLoader(context, context.getNamingToken(), getClass().getClassLoader());
}
}
}
//關(guān)閉tomcat服務(wù)
@Override
public void stop() throws WebServerException {
synchronized (this.monitor) {
boolean wasStarted = this.started;
try {
this.started = false;
try {
stopTomcat();
this.tomcat.destroy();
}
catch (LifecycleException ex) {
}
}
catch (Exception ex) {
thrownew WebServerException("Unable to stop embedded Tomcat", ex);
}
finally {
if (wasStarted) {
containerCounter.decrementAndGet();
}
}
}
}
使用外置tomcat部署
配置案例
外置Tomcat啟動SpringBoot源碼點擊這里
繼承SpringBootServletInitializer
- 外部容器部署的話,就不能依賴于Application的main函數(shù)了,而是要以類似于web.xml文件配置的方式來啟動Spring應(yīng)用上下文,此時需要在啟動類中繼承SpringBootServletInitializer,并重寫configure方法;還添加 @SpringBootApplication 注解,這是為了能掃描到所有Spring注解的bean
方式一:啟動類繼承SpringBootServletInitializer實現(xiàn)configure:
@SpringBootApplication
public class SpringBootHelloWorldTomcatApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}
}
這個類的作用與在web.xml中配置負責初始化Spring應(yīng)用上下文的監(jiān)聽器作用類似,只不過在這里不需要編寫額外的XML文件了。
方式二:新增加一個類繼承SpringBootServletInitializer實現(xiàn)configure:
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
//此處的Application.class為帶有@SpringBootApplication注解的啟動類
return builder.sources(Application.class);
}
}
pom.xml修改tomcat相關(guān)的配置
首先需要將 jar 變成war <packaging>war</packaging>
如果要將最終的打包形式改為war的話,還需要對pom.xml文件進行修改,因為spring-boot-starter-web中包含內(nèi)嵌的tomcat容器,所以直接部署在外部容器會沖突報錯。因此需要將內(nèi)置tomcat排除
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
在這里需要移除對嵌入式Tomcat的依賴,這樣打出的war包中,在lib目錄下才不會包含Tomcat相關(guān)的jar包,否則將會出現(xiàn)啟動錯誤。
但是移除了tomcat后,原始的sevlet也被移除了,因此還需要額外引入servet的包
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
注意的問題
此時打成的包的名稱應(yīng)該和 application.properties 的 server.context-path=/test 保持一致
<build>
<finalName>test</finalName>
</build>
如果不一樣發(fā)布到tomcat的webapps下上下文會變化
原理
tomcat不會主動去啟動springboot應(yīng)用 ,, 所以tomcat啟動的時候肯定調(diào)用了SpringBootServletInitializer的SpringApplicationBuilder , 就會啟動springboot。
ServletContainerInitializer的實現(xiàn)放在jar包的META-INF/services文件夾下,有一個名為javax.servlet.ServletContainerInitializer的文件,內(nèi)容就是ServletContainerInitializer的實現(xiàn)類的全類名。當servlet容器啟動時候就會去該文件中找到ServletContainerInitializer的實現(xiàn)類,從而創(chuàng)建它的實例調(diào)用onstartUp。這里就是用了SPI機制
HandlesTypes(WebApplicationInitializer.class)
- @HandlesTypes傳入的類為ServletContainerInitializer感興趣的
- 容器會自動在classpath中找到 WebApplicationInitializer,會傳入到onStartup方法的webAppInitializerClasses中
- Set<Class<?>> webAppInitializerClasses這里面也包括之前定義的TomcatStartSpringBoot
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {
@Override
public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
throws ServletException {
List<WebApplicationInitializer> initializers = new LinkedList<>();
if (webAppInitializerClasses != null) {
for (Class<?> waiClass : webAppInitializerClasses) {
// 如果不是接口 不是抽象 跟WebApplicationInitializer有關(guān)系 就會實例化
if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
try {
initializers.add((WebApplicationInitializer)
ReflectionUtils.accessibleConstructor(waiClass).newInstance());
}
catch (Throwable ex) {
thrownew ServletException("Failed to instantiate WebApplicationInitializer class", ex);
}
}
}
}
if (initializers.isEmpty()) {
servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
return;
}
servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
// 排序
AnnotationAwareOrderComparator.sort(initializers);
for (WebApplicationInitializer initializer : initializers) {
initializer.onStartup(servletContext);
}
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
// Logger initialization is deferred in case an ordered
// LogServletContextInitializer is being used
this.logger = LogFactory.getLog(getClass());
WebApplicationContext rootApplicationContext = createRootApplicationContext(servletContext);
if (rootApplicationContext != null) {
servletContext.addListener(new SpringBootContextLoaderListener(rootApplicationContext, servletContext));
}
else {
this.logger.debug("No ContextLoaderListener registered, as createRootApplicationContext() did not "
+ "return an application context");
}
}
SpringBootServletInitializer
protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) {
SpringApplicationBuilder builder = createSpringApplicationBuilder();
builder.main(getClass());
ApplicationContext parent = getExistingRootWebApplicationContext(servletContext);
if (parent != null) {
this.logger.info("Root context already created (using as parent).");
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);
builder.initializers(new ParentContextApplicationContextInitializer(parent));
}
builder.initializers(new ServletContextApplicationContextInitializer(servletContext));
builder.contextClass(AnnotationConfigServletWebServerApplicationContext.class);
// 調(diào)用configure
builder = configure(builder); //①
builder.listeners(new WebEnvironmentPropertySourceInitializer(servletContext));
SpringApplication application = builder.build();//②
if (application.getAllSources().isEmpty()
&& MergedAnnotations.from(getClass(), SearchStrategy.TYPE_HIERARCHY).isPresent(Configuration.class)) {
application.addPrimarySources(Collections.singleton(getClass()));
}
Assert.state(!application.getAllSources().isEmpty(),
"No SpringApplication sources have been defined. Either override the "
+ "configure method or add an @Configuration annotation");
// Ensure error pages are registered
if (this.registerErrorPageFilter) {
application.addPrimarySources(Collections.singleton(ErrorPageFilterConfiguration.class));
}
application.setRegisterShutdownHook(false);
return run(application);//③
}
① 當調(diào)用configure就會來到TomcatStartSpringBoot .configure,將Springboot啟動類傳入到builder.source
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}
② 調(diào)用SpringApplication application = builder.build(); 就會根據(jù)傳入的Springboot啟動類來構(gòu)建一個SpringApplication
public SpringApplication build(String... args) {
configureAsChildIfNecessary(args);
this.application.addPrimarySources(this.sources);
return this.application;
}
③ 調(diào)用 return run(application); 就會啟動springboot應(yīng)用
protected WebApplicationContext run(SpringApplication application) {
return (WebApplicationContext) application.run();
}
也就相當于Main函數(shù)啟動:
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
之后的流程就與上面 使用內(nèi)置Tomcat的Main函數(shù)一致了