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

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

简介 Spring Boot 的出现极大的简化了开发流程,封装了很多实用的工具;今天要说的是2.x版本中的异常处理,在Spring Boot中其实已经给我们实现好了异常处理方法;对应的ControllerBasicErrorController ,我们可以去实现它,改成自己的逻辑以及返回值,而且支持同步和异步。

通过解析源码我们知道,BasicErrorController 通过ErrorAttributes可以自定义返回属性,所以我们可以自定义一个ErrorAttributes类只要实现ErrorAttributes即可;默认Spring Boot 已经帮我们实现了一个DefaultErrorAttributes;如果我们想要改变其中属性我们只需要继承DefaultErrorAttributes即可,比如下面

不过这里有个小细节我们必须要注意getErrorAttributes第一个参数是WebRequest,为什么要说这个呢? 因为Spring Boot 2.x 还有一套DefaultErrorAttributes,名字长得一模一样,傻傻分不清;如果你发现自定义的ErrorAttributes无法起作用,可能就是包没引对。我们一起来看看

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

自动注册了MVC

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那就肯定不会起作用了,而且还有可能出现如下错误

***************************
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


转载于:https://my.oschina.net/itlangz/blog/3007388

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值