
已解决:org.springframework.boot.context.embedded.EmbeddedServletContainerException
在使用Spring Boot进行Web开发时,开发者有时会遇到org.springframework.boot.context.embedded.EmbeddedServletContainerException的异常。这种异常通常与嵌入式Servlet容器(例如Tomcat、Jetty等)配置相关。在启动Spring Boot应用程序时,嵌入式Servlet容器无法正确启动,从而抛出该异常。以下是一个典型场景:
场景:在Spring Boot项目中配置自定义的嵌入式Tomcat服务器,并尝试运行应用程序时,遇到启动失败的问题。
示例代码片段:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> customizer() {
return (factory) -> {
// 自定义配置,例如端口号或其他Tomcat设置
factory.setPort(8080);
};
}
}导致org.springframework.boot.context.embedded.EmbeddedServletContainerException报错的原因可能包括但不限于:
以下是一个可能导致该报错的代码示例,并解释其错误之处:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> customizer() {
return (factory) -> {
// 错误的自定义配置,例如无效的端口号
factory.setPort(-1);
};
}
}错误分析:
EmbeddedServletContainerException异常。为了正确解决该报错问题,我们需要确保端口号有效,并且项目中包含必要的依赖和正确的配置。以下是正确的代码示例:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> customizer() {
return (factory) -> {
// 正确的自定义配置,使用有效的端口号
factory.setPort(8080);
};
}
}同时,确保在pom.xml文件中包含必要的嵌入式Servlet容器依赖,例如:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>在编写和配置Spring Boot应用程序时,需要注意以下几点:
通过以上步骤和注意事项,可以有效解决org.springframework.boot.context.embedded.EmbeddedServletContainerException报错问题,确保Spring Boot应用程序的正常启动和运行。