在SpringBoot1中,配置错误页的方法我们可以通过如下方式:
@Configuration public class ErrorPageConfig{ @Bean public EmbeddedServletContainerCustomizer containerCustomizer() { return new EmbeddedServletContainerCustomizer() { @Override public void customize(ConfigurableEmbeddedServletContainer container) { ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error_401.html"); ErrorPage error405Page = new ErrorPage(HttpStatus.METHOD_NOT_ALLOWED, "/error_401.html"); ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/error_404.html"); ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error_500.html"); container.addErrorPages(error401Page,error405Page, error404Page, error500Page); } }; } }
但是在SpringBoot2中没有EmbeddedServletContainerCustomizer
这个类了,于是查了下文档可以使用如下方式实现:
@Component public class ErrorPageConfig implements ErrorPageRegistrar { @Override public void registerErrorPages(ErrorPageRegistry registry) { ErrorPage[] errorPages=new ErrorPage[2]; errorPages[0]=new ErrorPage(HttpStatus.NOT_FOUND,"/error-404.html"); errorPages[1]=new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR,"/error-500.html"); registry.addErrorPages(errorPages); } }