The @ControllerAdvice annotation

Some of the functionality we defined at the controller level can be common across the application. For example, we might want to use the same date format across the application. So, @InitBinder that we defined earlier can be applicable across the application. How do we achieve that? @ControllerAdvice helps us make the functionality common across all Request Mappings by default.

For example, consider the Controller advice example listed here. We use a @ControllerAdvice annotation on the class and define the method with @InitBinder in this class. By default, the binding defined in this method is applicable to all request mappings:

    @ControllerAdvice 
public class DateBindingControllerAdvice {
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new
SimpleDateFormat("dd/MM/yyyy");
binder.registerCustomEditor(Date.class,
new CustomDateEditor(
dateFormat, false));
}
}

Controller advice can also be used to define common model attributes (@ModelAttribute) and common exception handling (@ExceptionHandler). All you would need to do is create methods marked with appropriate annotations. We will discuss exception handling in the next section.