问题描述
我可以定义一个 Spring ControllerAdvice,它由使用自定义注解的控制器子集有选择地使用:
I can define a Spring ControllerAdvice that is selectively used by a subset of controllers using a custom annotation:
@RestController
@UseAdviceA
@RequestMapping("/myapi")
class ApiController {
...
}
@ControllerAdvice(annotations = UseAdviceA.class)
class AdviceA {
...
}
但是是否可以通过自定义注释传入一个属性,建议类可以从注释中获取?例如:
But is it possible to pass in an attribute via the custom annotation where the advice class can pick up from the annotation? For e.g.:
@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 也将不胜感激.
Any other way to achieve the same outcome, which is to be able to define a custom configuration at the Controller method which can be passed to the ControllerAdvice would be much appreciated too.
推荐答案
这里有一个解决方案.
给定
Here is a solution.
Given
@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);
}
这篇关于如何从 ControllerAdvice 类中的 ControllerAdvice 选择器中检索属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!