@ControllerAdvice
是 Spring Framework 中的一个注解,用于定义全局控制器异常处理器、绑定数据、或者模型属性。它是 @Component
注解的一个特殊化,主要用于对控制器进行增强。
1.全局异常处理
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred");
}
}
@ExceptionHandler(Exception.class)
:- 指定这个方法处理
Exception
类型的异常。 - 由于
Exception
是所有异常的基类,这个方法将捕获所有未被其他更具体的异常处理器捕获的异常。
- 指定这个方法处理
- 方法签名:
public ResponseEntity<String> handleException(Exception e)
- 接受一个
Exception
参数,允许访问异常详情。 - 返回
ResponseEntity<String>
,这允许我们自定义 HTTP 响应。
- 方法逻辑:
- 创建并返回一个
ResponseEntity
对象。 - 设置 HTTP 状态码为 500(内部服务器错误)。
- 设置响应体为字符串 "An error occurred"。
- 创建并返回一个
2. 全局数据绑定
@ControllerAdvice
public class GlobalDataBinder {
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
}
@ControllerAdvice
注解:
- 将这个类标记为全局控制器增强。
- 使得这个类中定义的方法(如
@InitBinder
、@ExceptionHandler
、@ModelAttribute
)可以应用到整个应用程序的所有控制器
3. 全局数据预处理
@ControllerAdvice
public class GlobalModelAttributes {
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("globalAttribute", "This is a global attribute");
}
}
- 使用
@ModelAttribute
注解来添加全局的模型属性。 - 这些属性将被添加到所有使用
@RequestMapping
注解的方法的模型中。