Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EmbeddedServletContainerCustomizer in spring boot 2.0

I try to migrate my app from spring boot 1.5 to 2.0 The problem is that I cannot find EmbeddedServletContainerCustomizer. Any ideas how to make it through?

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

Update: I found it as ServletWebServerFactoryCustomizer in org.springframework.boot.autoconfigure.web.servlet package.

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

But there is an error: Cannot resolve method

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

I also had to change import of new Error Page from org.springframework.boot.web.servlet to org.springframework.boot.web.server

like image 896
degath Avatar asked Mar 21 '18 12:03

degath


People also ask

What is EmbeddedServletContainerCustomizer?

public interface EmbeddedServletContainerCustomizer. Strategy interface for customizing auto-configured embedded servlet containers. Any beans of this type will get a callback with the container factory before the container itself is started, so you can set the port, address, error pages etc.

What is ServletWebServerFactory?

Interface ServletWebServerFactory This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. @FunctionalInterface public interface ServletWebServerFactory extends WebServerFactory. Factory interface that can be used to create a WebServer .

What is spring boot servlet initializer?

Spring Boot Servlet Initializer class file allows you to configure the application when it is launched by using Servlet Container. The code for Spring Boot Application class file for JAR file deployment is given below − package com.


1 Answers

From Spring Boot 2 on the WebServerFactoryCustomizer has replaced the EmbeddedServletContainerCustomizer:

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

Alternatively you might add a view controller like

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/unauthorized").setViewName("forward:/401.html");
}

and then your WebServerFactory should point to /unauthorized instead:

@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> webServerFactoryCustomizer() {
    return (factory) -> factory.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/unauthorized"));
}
like image 152
Shilan Avatar answered Oct 17 '22 08:10

Shilan