@ControllerAdvice is an annotation provided by Spring allowing you to write global code that can be applied to a wide range of controllers
varying from all controllers to a chosen package or even a specific annotation.
By default, @ControllerAdvice will apply to all classes that use the @Controller annotation(which extends to classes using @RestController).
If you wanted this to be more specific, there are a few properties provided that allow this.
To reduce the applicable classes down by package, you simply need to add the name of the package to the annotation.
When a package is chosen, it will be enabled for classes inside that package as well as sub-packages.
Multiple packages can also be chosen by following the same process but using an array instead of a singular string (all properties in @ControllerAdvice can be singular or multiple).
@ControllerAdvice("my.chosen.package")
@ControllerAdvice(value = "my.chosen.package")
@ControllerAdvice(basePackages = "my.chosen.package")
To enable @ControllerAdvice for all controllers inside the package that the class (or interface) lives in.
@ControllerAdvice(basePackageClasses = MyClass.class)
To apply to specific classes use assignableTypes.
@ControllerAdvice(assignableTypes = MyController.class)
If you want to apply it to controllers with certain annotations
The below snippet would only help controllers annotated with @RestController (which it covers by default) but will not include @Controller annotated classes.
@ControllerAdvice(annotations = RestController.class)
Helpful Post for more insight
[Understanding Spring’s @ControllerAdvice]
Source Code