如何將springboot轉稱外接tomcat啟動
正常情況下,我們開發 SpringBoot 專案,由於內建了Tomcat,所以專案可以直接啟動,部署到伺服器的時候,直接打成 jar 包,就可以運行了 (使用內建 Tomcat 的話,可以在 application.yml 中進行相關配置)
有時我們會需要打包成 war 包,放入外接的 Tomcat 中進行執行,步驟如下 (此處我用的 SpringBoot 版本為 2.1.1,Tomcat 的版本為 8.0)
一、排除內建 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>
二、將打包方式更改為 war
<packaging>war</packaging>
三、修改啟動類
使啟動類繼承 SpringBootServletInitializer 類,並覆蓋 configure 方法
@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(DemoApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
四、新增依賴
由於 SpringBootServletInitializer 類需要用到 servlet-api 的相關 jar 包,所以需要新增依賴
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
五、檢視結果
最後啟動專案,在瀏覽器中輸入 http://localhost:8037/project/test/helloWord 就可以看到結果了
@RestController
public class HelloController {
@GetMapping(value = "/hello")
public String hello() {
return "Hello World!!!";
}
}