一種ControllerAdvice失效的解決方案

在一個(gè)Controller中開啟?。繣xcetionHandler注解可以對(duì)該Controller中的方法進(jìn)行異常處理(返回統(tǒng)一的格式)

使用@ControllerAdvice注解 ,開啟全局異常
有時(shí)會(huì)出現(xiàn)失效的情況,即開啟了全局異常,也不能顯示出想要的格式

一般網(wǎng)上給出的資料都是說(shuō)掃描不到@ControllerAdvice,
給出兩種解決方案,
1.讓Controller extends?。繡ontrollerAdvice注解的類
2.給注解的類添加@ComponentScan,或者給@SpringBootApplication注解的主程序添加@ComponentScan注解

通過(guò)試驗(yàn)發(fā)現(xiàn)并不能解決問(wèn)題。

試驗(yàn)后發(fā)現(xiàn)把@ControllerAdvice改為@RestControllerAdvice就行了。

官網(wǎng)也沒(méi)有特別提醒這個(gè),以下是官網(wǎng)給出的示例:

// Target all Controllers annotated with @RestController
@ControllerAdvice(annotations = RestController.class)
public class ExampleAdvice1 {}

// Target all Controllers within specific packages
@ControllerAdvice("org.example.controllers")
public class ExampleAdvice2 {}

// Target all Controllers assignable to specific classes
@ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})
public class ExampleAdvice3 {}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容