zoukankan      html  css  js  c++  java
  • Advising controllers with the @ControllerAdvice annotation

     

    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));
        }

    Advising controllers with the @ControllerAdvice annotation

  • 相关阅读:
    VC 编译 MATLAB 的 mex 文件
    MATLAB 与 Excel 接口
    MATLAB 编译器的使用
    为什么安装了MinGW之后,还是不能在Matlab中使用mex?
    matlab文件操作
    matlab外部程序接口-excel
    数字图像加密-同态加密方案
    matlab数字图像简单的加密方法
    matlab中矩阵的表示与简单操作
    linux 安装eccodes环境
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/7700337.html
Copyright © 2011-2022 走看看