@ControllerAdvice
用来将带有
@ExceptionHandler
,@InitBinder
, or@ModelAttribute
方法应用到所有@Controller
类或其子集
Specialization of @Component
for classes that declare @ExceptionHandler
, @InitBinder
, or @ModelAttribute
methods to be shared across multiple @Controller
classes.
Classes with @ControllerAdvice
can be declared explicitly as Spring beans or auto-detected via classpath scanning. All such beans are sorted via AnnotationAwareOrderComparator, i.e. based on @Order
and Ordered
, and applied in that order at runtime. For handling exceptions the first @ExceptionHandler
to match the exception is used. For model attributes and InitBinder initialization, @ModelAttribute
and @InitBinder
methods will also follow @ControllerAdvice
order.
By default the methods in an @ControllerAdvice
apply globally to all Controllers. Use selectors annotations()
, basePackageClasses()
, and basePackages()
(or its alias value()) to define a more narrow subset of targeted Controllers. If multiple selectors are declared, OR logic is applied, meaning selected Controllers should match at least one selector. Note that selector checks are performed at runtime and so adding many selectors may negatively impact performance and add complexity.