Spring Boot 2.0.1打包War部署至Tomcat时出现IllegalStateException
Hey there, let's work through this IllegalStateException you're hitting when deploying your Spring Boot WAR to Tomcat. Based on your Gradle setup and common pitfalls with this stack, here are the most probable fixes to try:
1. Fix Embedded Tomcat Dependency Scope
The biggest culprit here is usually conflicting Tomcat dependencies between your Spring Boot app and the external Tomcat server. When building a WAR for external deployment, you need to mark Spring Boot's embedded Tomcat as providedRuntime so it doesn't get packaged into your WAR file. Update your dependencies block in Gradle like this:
dependencies { compile 'org.springframework.boot:spring-boot-starter-web' providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat' // Add any other project dependencies here }
This tells Gradle to use the embedded Tomcat during development but exclude it from the final WAR, preventing conflicts with the server's own Tomcat instance.
2. Add a ServletInitializer to Bootstrap Your App
Spring Boot WARs need a way to hook into the traditional servlet container lifecycle. Make sure your main application class extends SpringBootServletInitializer and overrides the configure method. Here's how that should look:
package api.abroad; 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 Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } }
Without this class, Tomcat won't know how to initialize your Spring Boot application, which often leads to an IllegalStateException.
3. Verify Your bootWar Configuration
Your current bootWar block looks correct, but double-check a couple of things:
- Ensure the
mainClassNameis fully qualified and matches the actual package and class name of your app's entry point. - Build the WAR using the
bootWartask (not the standardwartask) to get Spring Boot's specialized packaging. Run this command to generate the correct WAR:
./gradlew bootWar
4. Check Tomcat Version Compatibility
Spring Boot 2.0.1.RELEASE is designed to work with Tomcat 8.5.x or 9.x. If you're using an older version like Tomcat 7, you'll run into compatibility issues that can throw IllegalStateExceptions. Make sure your server is running a supported Tomcat version.
If these fixes don't resolve the issue, share the full stack trace of the IllegalStateException—this will help narrow down the exact problem, like a missing bean definition or configuration conflict.
内容的提问来源于stack exchange,提问作者ouyangjj

