The @ControllerAdvice
annotation is a component annotation allowing implementation classes to be auto-detected through
classpath scanning. It is automatically enabled when using the MVC namespace or the MVC Java config.
Classes annotated with @ControllerAdvice
can contain @ExceptionHandler
, @InitBinder
, and @ModelAttribute
annotated
methods, and these methods will apply to @RequestMapping
methods across all controller hierarchies as opposed to the controller
hierarchy within which they are declared.
The @ControllerAdvice
annotation can also target a subset of controllers with its attributes:
// Target all Controllers annotated with @RestController @ControllerAdvice(annotations = RestController.class) public class AnnotationAdvice {} // Target all Controllers within specific packages @ControllerAdvice("org.example.controllers") public class BasePackageAdvice {} // Target all Controllers assignable to specific classes @ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class}) public class AssignableTypesAdvice {}
Customizing data binding with @InitBinder
Annotating controller methods with @InitBinder
allows you to configure web data binding directly within your controller class. @InitBinder
identifies methods that initialize the WebDataBinder
that will be used to populate command and form object arguments of annotated handler
methods.
Such init-binder methods support all arguments that @RequestMapping
supports, except for command/form objects and corresponding
validation result objects. Init-binder methods must not have a return value. Thus, they are usually declared as void
. Typical arguments include
WebDataBinder
in combination with WebRequest
orjava.util.Locale
, allowing code to register context-specific editors.
The following example demonstrates the use of @InitBinder
to configure a CustomDateEditor
for all java.util.Date
form properties.
@InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); }