springboot 使用自定义注解,使用例子
时间: 2023-07-20 07:06:52 浏览: 115
以下是一个使用自定义注解的 Spring Boot 示例:
首先,定义一个自定义注解 `CustomAnnotation`:
```
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
String value() default "";
}
```
接下来,在 Spring Boot 的控制器中使用自定义注解 `CustomAnnotation`:
```
@RestController
@RequestMapping("/example")
public class ExampleController {
@CustomAnnotation("myAnnotation")
@GetMapping("/test")
public String test() {
return "Hello, world!";
}
}
```
最后,通过反射获取自定义注解 `CustomAnnotation` 的值:
```
@RestControllerAdvice
public class CustomAdvice {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex, HandlerMethod handlerMethod) throws Exception {
CustomAnnotation customAnnotation = handlerMethod.getMethodAnnotation(CustomAnnotation.class);
if (customAnnotation != null) {
String annotationValue = customAnnotation.value();
// 处理自定义注解逻辑
}
// 处理异常逻辑
}
}
```
在上面的示例中,当 `ExampleController` 中的 `test()` 方法抛出异常时,会调用 `CustomAdvice` 中的 `handleException()` 方法。通过反射获取 `test()` 方法上的自定义注解 `CustomAnnotation` 的值,并进行处理。
阅读全文
相关推荐
















