前言
使用springboot內嵌的tomcat啟動是沒問題,但是工程是要放到服務器上的tomcat的,所以springboot內嵌的能夠啟動,但不代表服務器的tomcat能啟動起來,我就遇到了這個問題,所以本地使用外部的tomcat啟動,模擬服務器的tomcat可以測試一下,有問題及時修復,不要等到放到服務器上時才發現問題
昨天遇到的問題,使用sprintboot自帶的tomcat啟動是沒問題的,但是使用外部的tomcat啟動一直沒有加載啟動類,排查了幾個小時沒解決;最后發現啟動沒有繼承SpringBootServletInitializer導致總結一下idea使用外部tomcat時遇到的坑
1.idea中配置tomcat(假設你的tomcat已經已下載且安裝好)
1.1選擇Edit Configuration選項
1.2 點擊加號選擇tomcat中的local
配置如圖所示,URL路徑,HTTP port 這里配置的是8080
1.3 Deployment的配置
選擇war包,注意后綴為war exploded不要選
1.4 環境變量的一些參數根據需要配置
1.5 點擊File->Project Structure
到此tomcat的配置就完成了
2.sprintboot的配置(假設sprintboot項目你已經建好了)
2.1 啟動類
- 修改啟動類,使其繼承SpringBootServletInitializer類,重寫configure方法。
- 如果SpringBoot幫我們建立了SpringBootServletInitializer類文件,直接刪掉,修改最開始的SpringBootApplication 項目啟動類,就是有main方法的那個
@SpringBootApplication(scanBasePackages = {"io.test"})
@EnableScheduling
public class BigscreenApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(BigscreenApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
logger.info("start BigscreenApplication with:" + System.getenv().toString());
return builder.sources(BigscreenApplication.class);
}
}
2.2 pom文件修改
因為要打成war所以需要起個名稱<finalName>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
<finalName>test</finalName>
</build>
2.3如果日志log4j2.xml配置未生效,可能是沒引入spring-boot-starter-logging
注意:spring-boot-starter-web中去除spring-boot-starter-logging依賴,否則日志jar包會有沖突,導致啟動失敗
<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>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
2.4 編譯時可能會報:Error java: 無法訪問javax.servlet.ServletException 找不到javax.servlet.ServletException的類文件
是因為缺少servlet的jar包引入即可
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency>