In Spring, the two following statements are, if I’m not mistaken, identical:
@RequestParam("type") String type
@RequestParam String type
How can spring know the variable name of ‘type’ (second version). I was under the impression
that this information was removed from the class files unless compiled with
the -g flag (include debug information).
The short version of this is that apparently the parameter names are being compiled in, if they weren’t, you’d get an exception indicating that Spring MVC couldn’t deduce the parameter name. That is, parameter names aren’t always stored in the bytecode, but it seems like if they are, Spring will find them, if not, you need to specify them when you add the
@RequestParamannotation.Other details are available on this similar question and it’s answers.
In 3.0.5.RELEASE, these annotations are processed in HandlerMethodInvoker.resolveHandlerArguments and it appears that if no value is supplied, Spring uses
RequestParam.value(). This can return the empty string.Further down, Spring uses
HandlerMethodInvoker.resolveRequestParam, and inside there, if the parameter name is empty, it invokesHandlerMethodINvoker.getRequiredParameterNamewithMethodParameter methodParamas an argument:Note that here it tries to pull the information from
methodParam, which, if we back up the tree, we see thatresolveHandlerArgumentsactually creates a newMethodParameterfor each argument that it processes. InsideMethodParameter, we can take a look atgetParameterName():So this uses something called a
ParameterNameDiscoverer, but this is an interface and my trace isn’t showing which implementation it’s using, there are a few. Looking at LocalVariableTableParameterNameDiscoverer.getParameterNames we end up calling aLocalVariableTableParameterNameDiscoverer.ParameterNameDiscoveringVisitoras part of anorg.objectweb.asm.ClassReader, which as far as I can tell tries to read the parameter name out of the bytecode.