TypechoJoeTheme

香草物语

统计
登录
用户名
密码
/
注册
用户名
邮箱
输入密码
确认密码

SpringBoot 之 @ControllerAdvice使用场景

Laughing博主
2020-09-27
/
0 评论
/
1,183 阅读
/
417 个字
/
百度已收录
09/27
本文最后更新于2024年03月18日,已超过185天没有更新。如果文章内容或图片资源失效,请留言反馈,我会及时处理,谢谢!

SpringBoot 之 @ControllerAdvice使用场景

@ControllerAdvice是spring 3.2版本增加的一个注解,@ControllerAdvice注解的类,可以应用到所有的@RequestMapping请求中,主要有三个应用场景:

  1. @ExceptionHandler 全局异常处理
  2. @InitBinder 全局数据预处理
  3. @ModelAttribute 全局数据绑定
    注意
  4. 如果这三个注解直接在@Controller类中使用,则只对当前控制器生效
  5. 如果@ControllerAdvice中不需要返回view,也可以使用@RestControllerAdvice,即@RestControllerAdvice = @ControllerAdvice + @ResponseBody

@ExceptionHandler 全局异常处理

定义全局异常处理类

/**
 * 全局异常处理
 * @author laughing
 * @date 2020/9/26
 * @site https://www.xiangcaowuyu.net
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理越界异常
     * @param indexOutOfBoundsException 越界异常
     * @return Map
     */
    @ExceptionHandler(IndexOutOfBoundsException.class)
    public Map<String,Object> indexOutOfBoundsException(IndexOutOfBoundsException indexOutOfBoundsException){
        Map<String,Object> map = new HashMap<>(2);
        map.put("code",400);
        map.put("msg","越界异常");
        return map;
    }

    /**
     * 处理空引用异常
     * @param nullPointerException 空引用
     * @return Map
     */
    @ExceptionHandler(NullPointerException.class)
    public Map<String,Object> nullPointerException(NullPointerException nullPointerException){
        Map<String,Object> map = new HashMap<>(2);
        map.put("code",400);
        map.put("msg","空引用异常");
        return map;
    }
}

@RestControllerAdvice注解到类上,@ExceptionHandler注解到具体的异常上,只有@ExceptionHandler注解的异常,才会进行处理,如上,系统只会处理IndexOutOfBoundsException以及NullPointerException异常,其他异常均不进行处理。

使用

/**
 * @author laughing
 * @date 2020/9/26
 * @site https://www.xiangcaowuyu.net
 */
@RestController
public class TestGlobalExceptionController {

    /**
     * 测试越界异常
     *
     * @return String
     */
    @RequestMapping("/testIndexOutOfBoundsException")
    public String testIndexOutOfBoundsException() {
        String[] names = {"张三"};
        return names[2];
    }

    /**
     * 测试空引用异常
     *
     * @return String
     */
    @RequestMapping("/testNullPointerException")
    public String testNullPointerException() {
        String firstName = null;
        String lastName = "laughing";
        return firstName.toLowerCase() + lastName;
    }

    /**
     * 这个异常不会被处理
     *
     * @return String
     */
    @RequestMapping("/exception")
    public String testException() throws Exception {
        throw new Exception("这个异常不会被处理");
    }

}

我们分别进行请求测试

@InitBinder 全局数据预处理

全局数据预处理可以在@RequestMapping方法前,先对数据进行处理,然后在进入@RequestMapping方法。

定义全局数据预处理类

/**
 * @author laughing
 * @date 2020/9/26
 * @site https://www.xiangcaowuyu.net
 */
@RestControllerAdvice
public class GlobalDataBinder {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                Date date = null;
                try {
                    if (text != null) {
                        date = DateUtils.addDays(DateUtils.parseDate(text,"yyyy-MM-dd"),1);
                    }
                } catch (ParseException e) {
                }
                setValue(date);
            }
        });
    }

}

使用

    @ModelAttribute
    @RequestMapping("/testGlobalDataBinderController")
    public Person testGlobalDataBinderController(@RequestParam("name") String name, @RequestParam("birthday")Date birthday){
        Person person = new Person();
        person.setBirthday(birthday);
        person.setName(name);
        return person;
    }

    @ModelAttribute
    @RequestMapping("/testGlobalDataBinderControllerBody")
    public Person testGlobalDataBinderControllerBody(@RequestBody Person person){
        return person;
    }

}

我们通过postman测试,可以发现日期已经自动加了一天

@ModelAttribute 全局数据绑定

全局数据绑定功能可以用来做一些初始化的数据操作,我们可以将一些公共的数据定义在添加了 @ControllerAdvice注解的类中,这样,在每一个 Controller 的接口中,就都能够访问导致这些数据。

定义全局数据绑定

/**

@RestController
public class TestGlobalDataAttributeController {

/**
 * 全局数据绑定
 * @author laughing
 * @date 2020/9/26
 * @site https://www.xiangcaowuyu.net
 */
@RestControllerAdvice
public class GlobalDataAttribute {

    @ModelAttribute(name = "person")
    public Map<String,Object> modelAttribute(){
        Map<String,Object> map = new HashMap<>();
        map.put("name","张三");
        return map;
    }

}

使用全局数据绑定

/**
 * @author laughing
 * @date 2020/9/26
 * @site https://www.xiangcaowuyu.net
 */
@RestController
public class TestGlobalDataAttributeController {

    /**
     * 测试
     * @param person 绑定模型
     * @return 绑定数据
     */
    @RequestMapping("/testGlobalDataAttribute")
    public Map<String, Object> testDataBinder(@ModelAttribute("person") Map<String, Object> person) {
        return person;
    }

}
Spring Boot
朗读
赞(0)
赞赏
感谢您的支持,我会继续努力哒!
版权属于:

香草物语

本文链接:

https://www.xiangcaowuyu.net/java/springboots-controlleradvice-usage-scenario.html(转载时请注明本文出处及文章链接)

评论 (0)
  1. 1 闲逛
    Windows 10 · MicroSoft Edge

    看看

    2018-09-01 回复
  2. […] 垃圾评论不会审核通过,请大家注意,具体细节,可以点击一下链接查看  关于网站加强评论审核通知 原文出自[ 木子网 ] 转载请保留原文链接: ht… […]

    2018-05-06 回复