Handling ambiguous handler methods mapped in REST application with Spring

岁酱吖の 提交于 2019-12-03 14:30:42

Spring can't distinguish if the request GET http://localhost:8080/api/brand/1 will be handled by getBrand(Integer) or by getBrand(String) because your mapping is ambiguous.

Try using a query parameter for the getBrand(String) method. It seems more appropriate, since you are performing a query:

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Brand getBrand(@PathVariable Integer id) {
    return brandService.getOne(id);
}

@RequestMapping(method = RequestMethod.GET)
public List<Brand> getBrand(@RequestParam(value="name") String name) {
    return brandService.getSome(name);
}

Using the approach described above:

  • Requests like GET http://localhost:8080/api/brand/1 will be handled by getBrand(Integer).
  • Requests like GET http://localhost:8080/api/brand?name=nike will be handled by getBrand(String).

Just a hint

As a good practice, always use plural nouns for your resources. Instead of /brand, use /brands.

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Brand getBrand(@PathVariable Integer id) {
    return brandService.getOne(id);
}

@RequestMapping(value = "/{name}", method = RequestMethod.GET)
public List<Brand> getBrand(@PathVariable String name) {
    return brandService.getSome(name);
}

When you run the app, and access the endpoints you tried coding up you realize the following, 'http://localhost:8086/brand/1' and 'http://localhost:8086/brand/FooBar' correspond to the same URL format (which can be described as protocol+endpoint+'brand'+). So SpringBoot is essentially confused if it should call the function 'getBrand' with a String datatype or an Integer. So to get over this I'd suggest you use a query parameter as mentioned by @cassiomolin or have separate paths for both invocations. This may be against the REST principles but assuming you are just doing a sample app this is another workaround.

@RequestMapping(value = "/id/{id}", method = RequestMethod.GET)
public Brand getBrand(@PathVariable Integer id) {
    return brandService.getOne(id);
}

@RequestMapping(value = "/name/{name}", method = RequestMethod.GET)
public List<Brand> getBrand(@PathVariable String name) {
    return brandService.getSome(name);
}

This worked for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!