@GetMapping、@PostMapping和@RequestMapping的区别
- 在Spring编写Controller的时候,在使用注解映射方法的时候还是比较混乱,在使用@GetMapping注解的时候,顺手写成了@RequestMapping ,但是发现还是实现了效果,两者能相互替换,但是换成PostMapping就报:Request method ‘GET’ not supported 的错误!所以我就来研究了一下这三者的区别,发现还确实有联系!
摘:Spring4.3中引进了{@GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping},来帮助简化常用的HTTP方法的映射,并更好地表达被注解方法的语义。
我们就来谈谈三者之间的区别及联系吧:
- @GetMapping
用于将HTTP GET请求映射到特定处理程序方法的注释。具体来说,@GetMapping是一个作为快捷方式的组合注释
@RequestMapping(method = RequestMethod.GET)。
Controller代码实现
@RestController
@RequestMapping("/msg")
@Slf4j
@Api(value = "kafka消息发送")
public class MsgController {
@Autowired
private KafkaTemplate<String,Object> kafkaTemplate;
@GetMapping(value = "message/send") //可以简写成@GetMapping("message/send")
public String send(String msg){
kafkaTemplate.send("test11", msg); //使用kafka模板发送信息
return "success";
}
}
测试请求:127.0.0.1:9999/msg/message/send?msg=测试getmapping请求

- @PostMapping
用于将HTTP POST请求映射到特定处理程序方法的注释。具体来说,@PostMapping是一个作为快捷方式的组合注释@RequestMapping(method = RequestMethod.POST)。
Controller代码实现
@RestController
@RequestMapping("/msg")
@Slf4j
@Api(value = "kafka消息发送")
public class MsgController {
@Autowired
private KafkaTemplate<String,Object> kafkaTemplate;
@PostMapping(value = "message/send") //可以简写成@PostMapping("message/send")
public String send(String msg){
kafkaTemplate.send("test11", msg); //使用kafka模板发送信息
return "success";
}
}
测试请求:127.0.0.1:9999/msg/message/send?msg=测试postmapping请求

- @RequestMapping
一般情况下都是用@RequestMapping(method=RequestMethod.),因为@RequestMapping可以直接替代以上两个注解,但是以上两个注解并不能替代@RequestMapping,@RequestMapping相当于以上两个注解的父类!
@RequestMapping(value = "message/send",method = RequestMethod.GET)。
Controller请求
@RestController
@RequestMapping("/msg")
@Slf4j
@Api(value = "kafka消息发送")
public class MsgController {
@Autowired
private KafkaTemplate<String,Object> kafkaTemplate;
@RequestMapping(value = "message/send",method = RequestMethod.GET)
public String send(String msg){
kafkaTemplate.send("test11", msg); //使用kafka模板发送信息
return "success";
}
}
测试请求(127.0.0.1:9999/msg/message/send?msg=测试request请求)

类似的组合注解还有:
- @PutMapping、@DeleteMapping、@PatchMapping
总结下来就是@PostMapping和@GetMapping都可以用@RequestMapping代替,如果读者怕在映射的时候出错,可以统一写@RequestMapping,当然这样写的话也有弊端,笼统的全用@RequestMapping, 不便于其他人对代码的阅读和理解!还是建议区分开来写!养成良好的代码习惯!
网友评论