關於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
相關文章
相關標籤/搜索