简体   繁体   中英

Spring MVC RestController Ambiguous PathVariable mapping

I have 2 GET handler methods

 @RestController
 public class TestController {

    ...

    @GetMapping(name = "/test")
    public Test testMethod() {
        return testService.getTest();
    }

    @GetMapping(name = "/test/{count}")
    public List<Test> getTestList2(@PathVariable(name = "count") Integer count) {

        return testService.getTestList(count);
    }
 }

And I get error:

Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'testController' method 
public java.util.List<models.Test> TestController.getTestList2(java.lang.Integer)
to {[],methods=[GET]}: There is already 'testController' bean method

If I comment one method all work fine

What you are doing mistake is you are telling @GetMapping name rather that its value, It might feel both of them works the same way but it has tiny differences.

RequestMapping.name : Assign a name to this mapping.

and

RequestMapping.value : The primary mapping expressed by this annotation. Supported at the type level as well as at the method level! When used at the type level, all method-level mappings inherit this primary mapping, narrowing it for a specific handler method .

@RestController
public class TestController {

     @GetMapping(value = "/test")
     public String testMethod() {
        return "Hello from test";
     }

     @GetMapping(value = "/test/{count}")
     public String testMethod(@PathVariable(value = "count") Integer count) {
        return "Hello from Parameterized Test. Count: " + count;
     }
}

Hence you are specifying the path or route of your Controller it all always preferable to specify the value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM