美文网首页
同一个Controller的@RequestMapping指向同

同一个Controller的@RequestMapping指向同

作者: 二十五_0415 | 来源:发表于2019-08-08 15:13 被阅读0次

首先是这种

@RequestMapping(value="/a")
    public String a() {
        return "a";
    }
    
    @RequestMapping(value="/a")
    public String d() {
        return "a";
    }

这个应该都知道了,肯定会报错的
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping.
错误信息也很明确Ambiguous mapping。

那是不是value的值一定不能一样呢,答案是否定的

@RestController
public class TestController {
    
    @RequestMapping(value="/a")
    public String a() {
        return "a";
    }
    
    @RequestMapping(value="/a", method = RequestMethod.HEAD)
    public ResponseEntity<Void> b() {
        return ResponseEntity.ok().header("b", "b").build();
    }
    
    @RequestMapping(value="/a", method = RequestMethod.GET)
    public String c() {
        return "c";
    }
}
1.png 2.png 3.png

从结果可以看出,只要指定不同method就行。而且会优先匹配对应的方法,没有才会执行没有指定method的@RequestMapping对应方法

相关文章

网友评论

      本文标题:同一个Controller的@RequestMapping指向同

      本文链接:https://www.haomeiwen.com/subject/tyexjctx.html