EmbeddedServletContainerCustomizer在spring boot 2.0中

deg*_*ath 8 java spring-boot

我尝试将我的应用程序从spring boot 1.5迁移到2.0问题是我找不到EmbeddedServletContainerCustomizer.任何想法如何通过?

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

更新: 我在org.springframework.boot.autoconfigure.web.servlet包中找到它作为ServletWebServerFactoryCustomizer.

@Bean
public ServletWebServerFactoryCustomizer customizer() {
    return container -> container.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthenticated"));
}
Run Code Online (Sandbox Code Playgroud)

但是有一个错误:无法解决方法

'addErrorPages(org.springframework.boot.web.server.ErrorPage)'

我还必须将新错误页面的导入更改org.springframework.boot.web.servletorg.springframework.boot.web.server

小智 8

我认为您需要ConfigurableServletWebServerFactory而不是ServletWebServerFactoryCustomizer

您可以在下面找到代码片段:

import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

@Configuration
public class ServerConfig {

    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory();
        factory.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthenticated"));
        return factory;
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码是针对Undertow的。对于tomcat,您需要替换UndertowServletWebServerFactoryTomcatServletWebServerFactory

您将需要在项目中添加以下依赖项(对于Maven):

<dependency>
    <groupId>io.undertow</groupId>
    <artifactId>undertow-servlet</artifactId>
    <version>2.0.26.Final</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)


Vad*_*rer 5

您不需要容器定制器来注册您的错误页面。实现为 lambda 的简单 bean 定义可以解决问题:

@Bean
public ErrorPageRegistrar errorPageRegistrar() {
    return registry -> {
        registry.addErrorPages(
            new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthenticated"),
        );
    };
}
Run Code Online (Sandbox Code Playgroud)