---
title: "@ControllerAdvice的使用"
author: "raymond.chen"
date: "2019-11-06T21:07:25Z"
tags: []
categories: ["编程语言"]
slug: "controlleradvice"
draft: false
lastmod: "2019-11-06T21:07:25Z"
id: 2509669
url: "https://chenjumin.iteye.com/blog/2509669"
---

1、全局异常处理

        结合@ExceptionHandler注解使用

        用于捕获Controller中抛出的指定类型的异常，从而达到不同类型的异常区别处理的目的。

 

2、全局数据绑定

        结合@ModelAttribute注解使用

        表示其标注的方法将会在目标Controller方法执行之前执行。

 

3、全局数据预处理

        结合@InitBinder注解使用

        用于request中自定义参数解析方式进行注册，从而达到自定义指定格式参数的目的。

```
//1. 给接口中的变量取别名
@PostMapping("/book")
public void addBook(@ModelAttribute("b") Book book, @ModelAttribute("a") Author author) {
    System.out.println(book);
    System.out.println(author);
}

//2. 进行请求数据预处理
@InitBinder("b")
public void b(WebDataBinder binder) {
    binder.setFieldDefaultPrefix("b.");
}

@InitBinder("a")
public void a(WebDataBinder binder) {
    binder.setFieldDefaultPrefix("a.");
}

//3. 发送请求
http://localhost/book?b.name=zhangsan&b.price=10&a.name=lisi&a.age=50
```