SpringBoot工程,默认内置了Tomcat容器,所以可以直接通过main函数启动即可运行。但是,如果想要将SpringBoot打成war包,然后将war部署到外部的Tomcat容器中,则需要进行一些额外的操作。下面是SpringBoot打成war包部署到外部Tomcat容器中的步骤。
开发环境
(1)创建一个SpringBoot工程
采用IDEA开发工具,创建一个maven工程,或者直接创建SpringBoot工程。工程目录结构如下:

(2)添加依赖
在pom.xml文件中,添加依赖:
- <!-- springboot父工程依赖 -->
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.3.0.RELEASE</version>
- <relativePath/>
- </parent>
- <!-- 依赖 -->
- <dependencies>
- <!-- web模块依赖 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <!-- tomcat依赖 war包部署方式时候添加该依赖 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-tomcat</artifactId>
- <scope>provided</scope>
- </dependency>
- </dependencies>
- <!-- 插件 -->
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
复制代码
(3)启动类中重写configure方法
在启动类Application中,继承【SpringBootServletInitializer】类,然后重写【configure】方法,并且在该类上面,添加注解【@ServletComponentScan】。
- package com.gitee.zblog;
- 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;
- /**
- * @version 1.0.0
- * @Description: #启动类
- * @Date: 2022/1/10 21:38
- * @Copyright (C) ZhuYouBin
- */
- @SpringBootApplication
- @ServletComponentScan // war包部署时候,添加该注解
- public class Application extends SpringBootServletInitializer {
- // war包部署时候,继承SpringBootServletInitializer类,重写configure方法
- @Override
- protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
- return application.sources(Application.class);
- }
- public static void main(String[] args) {
- SpringApplication.run(Application.class, args);
- }
- }
复制代码
(4)编写测试类
接着,编写一个测试控制器类【TestController】,用于启动工程后,测试是否能够访问成功。
- package com.gitee.zblog.test;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- /**
- * @version 1.0.0
- * @Description: #类描述
- * @Date: 2022/1/10 21:44
- * @Copyright (C) ZhuYouBin
- */
- @RestController
- @RequestMapping("/test")
- public class TestController {
- @GetMapping("/hello")
- protected String demo() {
- return "<h1>Hello World</h1>";
- }
- }
复制代码
(5)部署war包到tomcat,启动测试
IDEA中,添加一个【Tomcat】容器,然后将【war】包部署到容器中,最后启动工程。


启动工程,然后打开浏览器,访问测试地址:http://localhost:6250/zblog/test/hello,访问测试结果如下所示:

以上,就是如何将SpringBoot工程通过war包的方式部署到外部Tomcat容器中的步骤。

来源:https://blog.caogenba.net/qq_39826207/article/details/122441677
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |