Spring Boot 2.0部署Tomcat7报错:缺失ServletWebServerFactory bean无法启动上下文
Alright, let's tackle this problem head-on. That error you're seeing happens because of a few key mismatches between Spring Boot 2.0's defaults and what Tomcat 7 supports. Here's how to fix it step by step:
1. Fix Servlet Version Compatibility
Spring Boot 2.0 ships with Servlet API 3.1 by default, but Tomcat 7 only supports up to Servlet 3.0. You need to override this in your pom.xml to avoid compatibility issues:
<properties> <servlet-api.version>3.0.1</servlet-api.version> </properties> <dependencies> <!-- Override Servlet API version --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet-api.version}</version> <scope>provided</scope> </dependency> </dependencies>
2. Switch to WAR Packaging & Exclude Built-in Tomcat
Spring Boot apps default to JAR packaging with an embedded Tomcat, but to deploy to an external Tomcat 7, you need to switch to WAR and exclude the embedded container:
<!-- Update packaging type --> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- Exclude embedded Tomcat --> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <!-- Add Tomcat 7 servlet API as provided --> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-servlet-api</artifactId> <version>7.0.96</version> <!-- Use a stable Tomcat 7 version --> <scope>provided</scope> </dependency> </dependencies>
3. Adjust Your Application Entry Point
Your main application class needs to extend SpringBootServletInitializer so that the external Tomcat can bootstrap your Spring Boot app properly. Update it like this:
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 DemoApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(DemoApplication.class); } public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
4. Use the Correct Build & Deployment Workflow
- Stop using
mvn spring-boot:run(this command relies on the embedded Tomcat which you've excluded, hence the error). - Instead, run
mvn clean packageto build the WAR file. - Copy the generated WAR from the
targetdirectory into Tomcat 7'swebappsfolder. - Start Tomcat 7, and it will deploy your app automatically.
These changes should resolve the ServletWebServerFactory bean missing error and get your Spring Boot 2.0 app running on Tomcat 7 smoothly.
内容的提问来源于stack exchange,提问作者Ante Ereš

