You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 1.5迁移至2.0:EmbeddedServletContainerCustomizer找不到的解决办法

Spring Boot 2.0迁移:解决找不到EmbeddedServletContainerCustomizer的问题

嘿,这个问题我在从Spring Boot 1.5迁到2.0的时候也碰到过,刚好能给你详细说说怎么解决~

问题根源

Spring Boot 2.0对Web容器的基础设施做了全面重构,原来的EmbeddedServletContainerCustomizer(属于org.springframework.boot.context.embedded包)被标记为过时并最终移除,官方用全新的API替换了它——也就是你找到的ServletWebServerFactoryCustomizer,它位于org.springframework.boot.autoconfigure.web.servlet包下。

完整解决方案

你已经找对了替代类,这里给你补全完整的代码示例,对比新旧实现更清晰:

旧代码(Spring Boot 1.5)

import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;

@Bean
public EmbeddedServletContainerCustomizer customizer() {
    return container -> container.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthenticated"));
}

新代码(Spring Boot 2.0+)

import org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryCustomizer;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;

@Bean
public ServletWebServerFactoryCustomizer customizer() {
    return factory -> factory.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthenticated"));
}

或者你也可以用更通用的WebServerFactoryCustomizer接口来定义Bean,效果是一样的:

@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> customizer() {
    return factory -> factory.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthenticated"));
}

额外注意点

  • 除了自定义类的包路径变化,ErrorPage类也从org.springframework.boot.context.embedded.ErrorPage迁移到了org.springframework.boot.web.server.ErrorPage,记得同步修改导入语句
  • 如果你的项目是基于WebFlux的响应式应用,对应的替代类是ReactiveWebServerFactoryCustomizer,不过看你的代码是Servlet环境,这个就不用考虑啦

内容的提问来源于stack exchange,提问作者degath

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:38:29