其他分享
首页 > 其他分享> > 关于spring boot中 EmbeddedServletContainerCustomizer

关于spring boot中 EmbeddedServletContainerCustomizer

作者:互联网

EmbeddedServletContainerCustomizer这个在spring boot2.X的版本中就不再提供支持了貌似2.0版本还能用 ,用来提供对异常的处理。在支持EmbeddedServletContainerCustomizer的springboot版本中我们可以类似这样来配置异常处理和跳转
package com.dabai.springtest.error;

import org.springframework.boot.web.server.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

@Configuration
public class ErrorPageConfig {


    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return new EmbeddedServletContainerCustomizer() {
            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401");
                ErrorPage error405Page = new ErrorPage(HttpStatus.METHOD_NOT_ALLOWED, "/405");
                ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404");
                ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500");

                container.addErrorPages(error401Page,error405Page, error404Page, error500Page);
            }
        };
    }
}

在不支持的情况下需要这样

package com.dabai.springtest.error;

import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

@Component
public class ErrorPageConfig implements ErrorPageRegistrar {


    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        ErrorPage error400Page=new ErrorPage(HttpStatus.BAD_REQUEST,"/error400" );
        ErrorPage error401Page=new ErrorPage(HttpStatus.UNAUTHORIZED,"/error401");
        ErrorPage error500Page=new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR,"/error500");
        registry.addErrorPages(error400Page,error401Page,error500Page);
    }
    
}

 

其中

ErrorPageRegistrar接口:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.boot.web.server;

@FunctionalInterface
public interface ErrorPageRegistrar {
    void registerErrorPages(ErrorPageRegistry registry);
}
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.boot.web.server;

@FunctionalInterface
public interface ErrorPageRegistry {
    void addErrorPages(ErrorPage... errorPages);
}

 

标签:spring,boot,springframework,HttpStatus,ErrorPage,import,org,new,EmbeddedServletC
来源: https://www.cnblogs.com/notably/p/10710165.html