gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:48:29 25 4
gpt4 key购买 nike

我可以定义一个 Spring ControllerAdvice,它由使用自定义注解的 Controller 子集有选择地使用:

@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 的自定义配置,也将不胜感激。

最佳答案

这是一个解决方案。
鉴于

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

Controller

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

你的 Controller 建议应该是这样的

@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);
}

关于java - 如何从 ControllerAdvice 类中的 ControllerAdvice 选择器检索属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47882476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com