Spring Boot 工程打成war包,部署在tomcat中

1、修改打包方式,將pom.xml中默認的jar修改爲war

<packaging>war</packaging>

2、排除SpringBoot內置的Tomcat容器並添加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>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-tomcat</artifactId>
	<scope>provided</scope>
</dependency>

3、工程打成war需要入口類繼承SpringBootServletInitializer類

並重寫SpringApplicationBuilder 方法

package com.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;

@SpringBootApplication
@EnableCaching
@EnableRedisRepositories
@ServletComponentScan(basePackageClasses = {net.sf.ehcache.constructs.web.ShutdownListener.class})
public class Demo2Application extends SpringBootServletInitializer {
	public static void main(String[] args) {
		SpringApplication.run(Demo2Application.class, args);
	}

	/**
	 * 工程打成war需要繼承SpringBootServletInitializer,重寫SpringApplicationBuilder 方法
	 * @date 2020年3月5日
	 * @author binge
	 */
	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
		return builder.sources(Demo2Application.class);
	}
}

4、打包

使用外部Tomcat部署訪問的時候,application.properties(或者application.yml)中配置的
server.port=
server.servlet.context-path=
將失效,請使用Tomcat的端口。
爲了防止應用上下文所導致的項目訪問資源加載不到的問題,建議pom.xml文件中標籤下添加<finalName>您的工程名稱</finalName>標籤:

<build>
      <!-- 您的工程名稱應與application.properties(或application.yml)中context-path保持一致 -->
    <finalName></finalName>
    ....

war 打包命令:

war方式打包,使用外置Tomcat:mvn clean package -Dmaven.test.skip=true

clean是清除之前的包,-Dmaven.test.skip=true是忽略測試代碼

jar 打包命令

在項目目錄下(與pom.xml文件同級),使用mvn命令打包,運行:
jar 方式打包,使用內置Tomcat:mvn clean install -Dmaven.test.skip=true

運行:java -jar 包名.jar

5、部署

把生成的war包放置在tomcat/webapps/目錄下,啓動tomcat後,war包會自動解壓部署,完成。
此時訪問時需要添加工程名: http://localhost:8080/bshms
如果你程序習慣不用工程名,修改修改tomcat/conf/server.xml,配置文件:代碼如下

<Host name="localhost"  appBase=""
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false">
<Context docBase="webapps/bshms" path="/"  reloadable="true" ></Context>
       </Host>

其中

<Context docBase="webapps/bshms" path="/"  reloadable="true" ></Context>

中的bshms就是你的工程名, path對應的"/",就代表訪問時沒有工程路徑名。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章