[英]Check if a controller has a @RequestHeader dynamically (in a test)
Using SpringBoot I managed to get the list of all controllers dynamically (in a test) using RequestMappingHandlerMapping
, but I cannot check if the controller uses the @RequestHeader("language") or not.使用 SpringBoot,我设法使用RequestMappingHandlerMapping
动态(在测试中)获取所有控制器的列表,但我无法检查 controller 是否使用 @RequestHeader("language") 。 Is there a way to retrieve this information?有没有办法检索这些信息? I don't think it's possible from RequestMappingHandlerMapping
.我认为RequestMappingHandlerMapping
不可能。
Thanks.谢谢。
public void randomApi(@PathVariable("user") String user,
@RequestHeader("language") String language){...}
RequestMappingHandlerMapping
represents all controller methods, you have to get a particular controller method that you are interested from it first. RequestMappingHandlerMapping
代表所有 controller 方法,您必须首先从中获取您感兴趣的特定 controller 方法。 The easiest way to do it is first give a name to the controller method such as GetRandomApi
:最简单的方法是首先为 controller 方法命名,例如GetRandomApi
:
@GetMapping(name = "GetRandomApi" , value= "/random")
public void randomApi(@PathVariable("user") String user, @RequestHeader("language") String language){
}
and then get the controller method by this name:然后通过此名称获取 controller 方法:
HandlerMethod hm = mapping.getHandlerMethodsForMappingName("GetRandomApi").get(0);
Please note HandlerMethod
represents a controller method and I assume you only has one controller method with this name.请注意HandlerMethod
代表 controller 方法,我假设您只有一个具有此名称的 controller 方法。
To check if this controller method has a parameter which is annotated with @RequestHeader
, you can do something likes:要检查此 controller 方法是否具有使用@RequestHeader
注释的参数,您可以执行以下操作:
for( MethodParameter param : hm.getMethodParameters()){
RequestHeader requestHeader = param.getParameterAnnotation(RequestHeader.class);
if(requestHeader != null) {
System.out.println(String.format("parameter index %s is annotated with @RequestHeader with the value %s",
param.getParameterIndex(),
requestHeader.value()));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.