簡體   English   中英

如何從ControllerAdvice類中的ControllerAdvice選擇器檢索屬性

[英]How to retrieve attribute from ControllerAdvice selector in ControllerAdvice class

我可以定義一個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的自定義配置,也將非常受歡迎。

這是一個解決方案。
特定

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM