简体   繁体   English

spring-boot 中的 @ControllerAdvice 注释是什么,我们为什么以及何时使用它?

[英]What is @ControllerAdvice annotation in spring-boot and why we use it and when?

我在基于 spring-boot 框架的工作中使用自定义框架,当我需要它来创建自定义异常处理程序类时,我在 spring-boot 中看到这个注释@ControllerAdvice但我不知道为什么我必须使用它?

@ ControllerAdvice is very useful to handle exceptions when you have multiple REST API controllers doing a lot of different work. @当你有多个REST API控制器做了很多不同的工作ControllerAdvice是来处理异常是非常有用的。

That means when writing any application you encounter exceptions and to handle them at each method level is tedious and not optimal.这意味着在编写任何应用程序时,您会遇到异常并在每个方法级别处理它们是乏味且不是最佳的。 So in order to overcome that, spring has introduced the concept of @ControllerAdvice which will intercept all the controllers and look for the exceptions thrown.因此,为了克服这个问题,spring 引入了@ControllerAdvice的概念,它将拦截所有控制器并查找抛出的异常。 This is at a global level means you only have one @ControllerAdvice for each application and it will intercept the exceptions thrown by the controllers in that particular application context.这是在全局级别意味着每个应用程序只有一个@ControllerAdvice ,它将拦截控制器在该特定应用程序上下文中抛出的异常。 For more information here is a nice explanation: 有关更多信息,这里有一个很好的解释:

Note : It should be used only with spring MVC controllers.注意:它应该只与 spring MVC 控制器一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM