@RestControllerAdvice注解
时间: 2024-01-19 15:18:23 浏览: 75
@RestControllerAdvice注解是Spring框架中的一个注解,用于定义全局的异常处理和全局数据绑定。它可以被用于标记一个类,该类将会被自动注册为全局异常处理器和全局数据绑定器。
与@ControllerAdvice注解相比,@RestControllerAdvice注解继承了@ControllerAdvice注解的属性annotations。这意味着,除了具有@ControllerAdvice注解的功能外,@RestControllerAdvice注解还可以通过annotations属性来指定需要处理的控制器注解类型。
下面是一个使用@RestControllerAdvice注解的示例:
```java
@RestControllerAdvice(annotations = RestController.class)
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
// 处理异常的逻辑
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error");
}
@ModelAttribute
public void addAttributes(Model model) {
// 添加全局数据绑定的逻辑
model.addAttribute("globalAttribute", "Global Attribute");
}
}
```
在上面的示例中,我们使用@RestControllerAdvice注解标记了一个类GlobalExceptionHandler。该类中的handleException方法用于处理所有的Exception类型的异常,并返回一个表示服务器内部错误的响应。而addAttributes方法用于添加全局数据绑定的属性。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)