Issue
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. Is there a way to retrieve this information?
I don't think it's possible from RequestMappingHandlerMapping
.
Thanks.
public void randomApi(@PathVariable("user") String user,
@RequestHeader("language") String language){...}
Solution
RequestMappingHandlerMapping
represents all controller methods, you have to get a particular controller method that you are interested from it first. The easiest way to do it is first give a name to the controller method such as 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 :
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.
To check if this controller method has a parameter which is annotated with @RequestHeader
, you can do something likes:
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()));
}
}
Answered By - Ken Chan
Answer Checked By - David Goodson (JavaFixing Volunteer)