Springboot使用外部的Servelt容器(最简单的方式)
第一步、修改POM.xml文件
将SpringBoot内置的Tomcat排除替换原有的部分依赖并添加api依赖
<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>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId></dependency>
第二步、修改启动类
需要继承SpringBootServletInitializer
package com.qcby.springbootusemvc;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;@SpringBootApplication
public class SpringbootusemvcApplication extends SpringBootServletInitializer {public static void main(String[] args) {SpringApplication.run(SpringbootusemvcApplication.class, args);}protected SpringApplicationBuilder configure(SpringApplicationBuilder builder){return builder.sources(SpringbootusemvcApplication.class);}
}
第三步、添加controller
package com.qcby.springbootusemvc.controller;import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/exam")
public class ExampleController {/*** Springboot 使用外部的tomcat** @Author 刘庆亮* @Date 2025-07-22 16:26* @param: null* @return null*/@GetMapping("/getCity")public String getCityInfo() {return "杭州";}}
第四步、添加外部的Tomcat
第五步、添加application.yaml
server:port: 18081servlet:context-path: /example-demo
第六步、启动(不许再启动类哪里启动一定要在下面标注的地方在启动!!!)
最后一步、在网址搜索 http://localhost:8080/hub_demo/exam/getCity
代码已经放到远程仓库需要自取
地址https://gitee.com/liu-qing_liang/spring-boot-exclsion-tomcat