小编典典

如何从ControllerAdvice类的ControllerAdvice选择器检索属性

spring-boot

我可以定义一个Spring ControllerAdvice,它由一个使用自定义注释的控制器子集选择性地使用:

@RestController
@UseAdviceA
@RequestMapping("/myapi")
class ApiController {
 ...
}

@ControllerAdvice(annotations = UseAdviceA.class)
class AdviceA {

 ...
}

但是是否可以通过自定义注释传递属性,建议类可以从注释中获取建议?例如:

@RestController
@UseAdviceA("my.value")
@RequestMapping("/myapi")
class ApiController {
 ...
}

@ControllerAdvice(annotations = UseAdviceA.class)
class AdviceA {
 // Some way to get the string "myvalue" from the instance of UseAdviceA
 ...
}

能够实现相同结果的任何其他方法,也就是能够在Controller方法中定义自定义配置的方法,都可以将其传递给ControllerAdvice,这一点也将不胜感激。


阅读 440

收藏
2020-05-30

共1个答案

小编典典

这是一个解决方案。
给定

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UseAdviceA {
  public String myValue();
}

控制者

@RestController
@UseAdviceA(myValue = "ApiController")
@RequestMapping("/myapi")
class ApiController {
 ...
}

您的控制器建议应类似于

@ControllerAdvice(annotations = {UseAdviceA.class})
class AdviceA {

  @ExceptionHandler({SomeException.class})
  public ResponseEntity<String> handleSomeException(SomeException pe, HandlerMethod handlerMethod) {
    String value = handlerMethod.getMethod().getDeclaringClass().getAnnotation(UseAdviceA.class).myValue();
     //value will be ApiController
    return new ResponseEntity<>("SomeString", HttpStatus.BAD_REQUEST);
  }
2020-05-30