下文笔者讲述controllerAdvice简介说明,如下所示
controllerAdvice简介
`@ControllerAdvice`是Spring MVC提供一个注解
用于定义
全局的、跨多个 Controller增强逻辑
它可以将一些通用的操作(如异常处理、数据绑定、模型属性等)集中管理
避免在每个Controller 中重复编写代码。
controllerAdvice主要用途
功能 | 对应方法 |
全局异常处理 | `@ExceptionHandler` |
全局模型属性 | `@ModelAttribute` |
全局数据绑定 | `@InitBinder` |
controllerAdvice基本结构示例
@ControllerAdvice
public class GlobalControllerAdvice {
// 全局异常处理
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
// 全局模型属性(所有 Controller 的 Model 都会包含)
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("globalMessage", "This is a global message.");
}
// 全局数据绑定器初始化
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.setDisallowedFields("id"); // 禁止某些字段被自动绑定
}
}
controllerAdvice使用场景详解
1.全局异常处理(推荐使用)
适用于统一返回错误信息、日志记录、权限失败处理等。
-使用`@ExceptionHandler`拦截特定异常。
-推荐配合`@ResponseStatus`
或
自定义响应体返回统一格式。
2.全局模型属性注入
通过`@ModelAttribute`
向所有Controller返回视图中添加共享数据(如用户信息、菜单项等)
3.数据绑定控制
使用`@InitBinder`控制参数绑定行为
例:
-禁用某些字段绑定(防止恶意修改ID字段)
-自定义日期格式转换器等
controllerAdvice与`@RestControllerAdvice`区别
注解 | 是否支持 `@ResponseBody` | 适用范围 |
`@ControllerAdvice` | ❌(需配合`@ResponseBody`才能返回JSON) | 返回视图名称的传统 MVC 场景 |
`@RestControllerAdvice` | ✅(默认返回 JSON) | RESTful API 场景 |
例:REST全局异常处理器
@RestControllerAdvice
public class RestGlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleResourceNotFound() {
ErrorResponse error = new ErrorResponse("Resource not found", 404);
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidationErrors(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach((error) -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}
}
controllerAdvice总结
特性 | 说明 |
作用范围 | 应用于所有 Controller,可指定包路径 |
可维护性 | 高,适合统一处理异常、模型属性、绑定逻辑 |
推荐使用场景 | 异常统一处理、REST API 错误响应、表单校验拦截等 |