@RestControllerAdvice中annotations
时间: 2023-11-18 11:51:11 浏览: 34
@RestControllerAdvice中的annotations属性用于指定需要被拦截的@Controller注解。通过在annotations属性中指定@Controller的子注解,可以限定只有被指定注解修饰的Controller才会被@RestControllerAdvice所拦截。这样可以更加细粒度地控制拦截的范围,以满足不同的业务需求。
相关问题
@RestControllerAdvice注解
@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方法用于添加全局数据绑定的属性。
@RestControllerAdvice什么作用
@RestControllerAdvice注解是一个用于定义全局RESTful异常处理类的类级别注解。通过使用@RestControllerAdvice和@ExceptionHandler注解,你可以实现在整个应用程序范围内统一处理RESTful风格的异常。它自动将异常处理方法的返回值转换为HTTP响应的主体,使得代码更加简洁、可读和可维护。与@ControllerAdvice注解相比,@RestControllerAdvice注解继承了@ControllerAdvice注解的属性annotations,并且专门用于处理RESTful风格的异常。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [@RestControllerAdvice注解](https://blog.csdn.net/jiayoudangdang/article/details/130473316)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)