@RequestMapping一个坑
@RequestMapping一个坑
今天发现了RequestMapping注解的一个坑:
当RequestMapping用于Class上时,不能用1.0,v1.0这样带小数点的value值做开头
@Controller
@RequestMapping(value = "/v1.0")
public class TestController {
@RequestMapping(value = "/a", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody
Object getA() {
return "{\"test\" : \"a\"}";
}
@RequestMapping(value = "/b", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody
Object getB() {
return "{\"test\" : \"b\"}";
}
}
如上代码运行后,访问http://localhost:port/v1.0/a 或者http://localhost:port/v1.0/b 时都会报错:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'testController' bean method
public java.lang.Object com.my.test.controller.TestController.getB()
to {[/v1.0],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}: There is already 'testController' bean method
单看异常信息,还以为是有重名的路径,结果搜遍了工程也没找到重名的类,后来"v1.0"改成"v1",就正常运行了。
顺带测试了下,发现改成1.0也是同样的错误。
之后再把一个方法上RequestMapping的value去掉,采用默认写法:
@RequestMapping("/b")
public @ResponseBody
Object getB() {
return "{\"test\" : \"b\"}";
}
再运行起来,访问http://localhost:port/v1.0/a或者http://localhost:port/v1.0/b 就会变成404错误。
HTTP Status 404 - /v1.0/a
type Status report
message /v1.0/a
description The requested resource is not available.
没深究根本原因,估计是Spring的小bug,以后避免带小数点的路径头。