关于Spring Boot 2.x 自定义ErrorAttributes 不起做用的问题解决

关于Spring Boot 2.x 自定义 ErrorAttributes 不起做用的问题解决

简介 Spring Boot 的出现极大的简化了开发流程,封装了不少实用的工具;今天要说的是2.x版本中的异常处理,在Spring Boot中其实已经给咱们实现好了异常处理方法;对应的ControllerBasicErrorController ,咱们能够去实现它,改为本身的逻辑以及返回值,并且支持同步和异步。java

经过解析源码咱们知道,BasicErrorController 经过ErrorAttributes能够自定义返回属性,因此咱们能够自定义一个ErrorAttributes类只要实现ErrorAttributes便可;默认Spring Boot 已经帮咱们实现了一个DefaultErrorAttributes;若是咱们想要改变其中属性咱们只须要继承DefaultErrorAttributes便可,好比下面 react

不过这里有个小细节咱们必需要注意getErrorAttributes第一个参数是WebRequest,为何要说这个呢? 由于Spring Boot 2.x 还有一套DefaultErrorAttributes,名字长得如出一辙,傻傻分不清;若是你发现自定义的ErrorAttributes没法起做用,可能就是包没引对。咱们一块儿来看看web

org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration

自动注册了MVCspring

org.springframework.boot.web.servlet.error.DefaultErrorAttributes

以下
编程

org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration

也注册了一套webflux异步

org.springframework.boot.web.reactive.error.DefaultErrorAttributes

怎么样看清楚了吗,名字如出一辙,包名不同,功能也如出一辙, 这里有个新概念webflux,不懂的同窗自动跳转 实战Spring Boot 2.0 Reactive编程系列 - WebFlux初体验 默认状况Spring Boot走的的是MVC的,因此若是你继承的是webfluxDefaultErrorAttributes那就确定不会起做用了,并且还有可能出现以下错误ide

***************************
APPLICATION FAILED TO START
***************************

Description:

The bean 'errorAttributes', defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [com/micro/cfg/CfgErrorAttributes.class] and overriding is disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
相关文章
相关标签/搜索