前言:當我們使用Spring Boot編寫了一個批處理應用程式,該程式隻是用于背景跑批資料,此時不需要内嵌的tomcat,簡化啟動方式使用非web方式啟動項目,步驟如下:
1、修改pom.xml檔案
在pom.xml檔案中去除内嵌tomcat,添加servlet依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<!--去除内嵌tomcat -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--添加servlet的依賴-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>compile</scope>
</dependency>
2、設定打包方式
在pom.xml檔案中将打項目包方式設定成jar,打成jar包通過指令去執行jar
<packaging>jar</packaging>
3、禁用web程式啟動方式
對于非Web應用程式,請在屬性檔案中禁用Web應用程式類型,application.yml檔案中添加:
spring:
main:
web-application-type: none
4、在啟動類中擴充
繼承SpringBootServletInitializer 類,以下本人寫了一個測試方法,項目啟動後生成一個txt檔案進行測試
@SpringBootApplication
public class TestiopojApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
System.out.println("項目開始啟動,開始執行任務============");
SpringApplication.run(TestiopojApplication.class, args);
String file = "E:\\copyFile";//檔案存放路徑
String fileName = "test測試";//生成的檔案名
String strContext = "測試成功=======";//檔案内容
try {
FileUtils.writeStringToFile((new File(file + File.separator + fileName + ".txt")), strContext, "UTF-8");
System.out.println("檔案建立成功============");
} catch (IOException e) {
System.out.println("檔案建立失敗============");
}
}
}
5、實列測試結果
由此我們可以通過java -jar 運作打包後的項目jar,控制台顯示Spring Boot啟動标志,項目正常啟動,檔案也正常建立成功,大功告成!

文章參考:點我點我點我
個人總結:
我是南國以南i記錄點滴每天成長一點點,學習是永無止境的!轉載請附原文連結!!!