SpringBoot工程,默认内置了Tomcat容器,所以可以直接通过main函数启动即可运行。但是,如果想要将SpringBoot打成war包,然后将war部署到外部的Tomcat容器中,则需要进行一些额外的操作。下面是SpringBoot打成war包部署到外部Tomcat容器中的步骤。
(1)创建一个SpringBoot工程开发环境
IDEA开发工具Tomcat容器
采用IDEA开发工具,创建一个maven工程,或者直接创建SpringBoot工程。工程目录结构如下:
(2)添加依赖在pom.xml文件中,添加依赖:
org.springframework.boot
spring-boot-starter-parent
2.3.0.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-tomcat
provided
org.springframework.boot
spring-boot-maven-plugin
(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;
@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;
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/hello")
protected String demo() {
return "Hello World";
}
}
(5)部署war包到tomcat,启动测试
IDEA中,添加一个【Tomcat】容器,然后将【war】包部署到容器中,最后启动工程。
启动工程,然后打开浏览器,访问测试地址:http://localhost:6250/zblog/test/hello,访问测试结果如下所示:
以上,就是如何将SpringBoot工程通过war包的方式部署到外部Tomcat容器中的步骤。



