控制器建议

@ExceptionHandler,@InitBinder@ModelAttribute方法仅适用于@Controller类或类层次结构,在其中声明它们。相反,如果他们 在@ControllerAdvice@RestControllerAdvice类,然后他们申请 到任何控制器。此外,从 5.3 开始,@ExceptionHandler方法@ControllerAdvice可用于处理来自任何@Controller或任何其他处理程序。spring-doc.cadn.net.cn

@ControllerAdvice元注释为@Component因此可以注册为 通过组件扫描的 Spring bean。spring-doc.cadn.net.cn

@RestControllerAdvice是一个快捷方式注释,它结合了@ControllerAdvice@ResponseBody,实际上只是一个@ControllerAdvice其异常处理程序 方法呈现给响应体。spring-doc.cadn.net.cn

启动时,RequestMappingHandlerMappingExceptionHandlerExceptionResolver检测 控制器通知 bean 并在运行时应用它们。全球@ExceptionHandler方法 从@ControllerAdvice在本地之后应用,从@Controller. 相比之下,全球@ModelAttribute@InitBinder方法在本地方法之前应用。spring-doc.cadn.net.cn

默认情况下,两个@ControllerAdvice@RestControllerAdvice适用于任何控制器, 包括@Controller@RestController.使用注释的属性缩小范围 它们所应用的控制器和处理程序集。例如:spring-doc.cadn.net.cn

// 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 {}
// Target all Controllers annotated with @RestController
@ControllerAdvice(annotations = [RestController::class])
class ExampleAdvice1

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

// Target all Controllers assignable to specific classes
@ControllerAdvice(assignableTypes = [ControllerInterface::class, AbstractController::class])
class ExampleAdvice3

前面示例中的选择器在运行时进行评估,可能会产生负面影响 如果广泛使用,性能。请参阅@ControllerAdvicejavadoc 了解更多详情。spring-doc.cadn.net.cn