gabi197
gabi197

Reputation: 113

How can Spring match query parameter only by formal parameter name?

Suppose I have the following code snippet:

@RequestMapping(method = RequestMethod.GET)
public List<Article> getArticles(@RequestParam int offset,
                                 @RequestParam int limit) {
  ...
}

How can Spring match the HTTP query parameters to the right formal parameters, when the parameter name is not explicitly stated as an annotation parameter?

Does it suppose the formal parameter names are always present in bytecode?

As I understand, it does not always have to be so. The formal parameter names can be retrieved from bytecode only when:

a) the class file has been compiled with -parameters javac option

b) the class file has been compiled with -g (or -g:vars) javac option, which adds debug information including the true variable names (since the formal parameters are stored as the first local variables of method)

Upvotes: 10

Views: 1668

Answers (1)

Oleksandr Pyrohov
Oleksandr Pyrohov

Reputation: 16226

To find the answer to your question, I built my Spring REST app with maven and using the following command:

mvn clean install -X

My build.log contained the following debug information:

[DEBUG] Command line options:

... -g -nowarn -target 1.8 -source 1.8 -encoding UTF-8

As we can see, the  -g  option is present by default, which generates debug information, including local variables.

To prove otherwise, I updated the maven-compiler-plugin config with the following option:

-g:none

Config example:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <compilerArgument>-g:none</compilerArgument>
            </configuration>
        </plugin>
    </plugins>
</build>

After that, my web service started to throw an error:

java.lang.IllegalArgumentException: Name for argument type [java.lang.String] not
available, and parameter name information not found in class file either.

Seems like the maven-compiler-plugin includes the -g option by default. And this allows Spring to retrieve parameter names at runtime.

Upvotes: 7

Related Questions