@GetMapping和@RequestMapping(method = RequestMethod.GET)有什么区别? 我在一些Spring Reactive的例子中看到过 使用@GetMapping代替@RequestMapping
当前回答
`@RequestMapping` since 2.5
可以处理所有HTTP方法
=>适用于类和方法
=>可以用来代替@Controller和@RestController,如果我们使用它 和@Component一起。
`@GetMapping` since 4.3
=>只能处理HTTP的GET方法
=>仅适用于方法
@GetMapping是@RequestMapping(method = RequestMethod.GET)的特定类型。两者都支持消费
其他回答
简短的回答:
语义上没有区别。
具体来说,@GetMapping是一个组合注释,充当 @RequestMapping(method = RequestMethod.GET)的快捷方式。
进一步阅读:
RequestMapping可以在类级别使用:
这个注释既可以在类级别使用,也可以在方法级别使用。 在大多数情况下,在方法级应用程序更倾向于使用一个 HTTP方法的特定变量@GetMapping, @PostMapping @PutMapping, @DeleteMapping或@PatchMapping。
而GetMapping只适用于方法:
将HTTP GET请求映射到特定处理程序的注释 方法。
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/GetMapping.html
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html
`@RequestMapping` since 2.5
可以处理所有HTTP方法
=>适用于类和方法
=>可以用来代替@Controller和@RestController,如果我们使用它 和@Component一起。
`@GetMapping` since 4.3
=>只能处理HTTP的GET方法
=>仅适用于方法
@GetMapping是@RequestMapping(method = RequestMethod.GET)的特定类型。两者都支持消费
@RequestMapping是一个类级别
@GetMapping是一个方法级
使用sprint Spring 4.3。现在情况已经发生了变化。现在您可以在处理http请求的方法上使用@GetMapping。类级@RequestMapping规范使用(方法级)@GetMapping注释进行了细化
这里有一个例子:
@Slf4j
@Controller
@RequestMapping("/orders")/* The @Request-Mapping annotation, when applied
at the class level, specifies the kind of requests
that this controller handles*/
public class OrderController {
@GetMapping("/current")/*@GetMapping paired with the classlevel
@RequestMapping, specifies that when an
HTTP GET request is received for /order,
orderForm() will be called to handle the request..*/
public String orderForm(Model model) {
model.addAttribute("order", new Order());
return "orderForm";
}
}
在Spring 4.3之前,它是@RequestMapping(method=RequestMethod.GET)
额外阅读克雷格·沃尔斯所著的一本书
@GetMapping是一个组合注释,作为@RequestMapping(method = RequestMethod.GET)的快捷方式。
@GetMapping是更新的注释。 它支持消费
消费选项有:
消费= "text/plain" 消费= {"text/plain", "application/*"}
详情见: GetMapping注释
或阅读: 请求映射变量
RequestMapping也支持消费
GetMapping我们只能应用在方法级,RequestMapping注释我们可以应用在类级和方法级
如图所示:
具体来说,@GetMapping是一个组合注释,充当 @RequestMapping(method = RequestMethod.GET)的快捷方式。 @GetMapping和@RequestMapping的区别 @GetMapping支持像这样的消费属性 @RequestMapping。
推荐文章
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式
- 如何从线程捕获异常
- 无法解析主机"<URL here>"没有与主机名关联的地址
- 如何在Java中打印二叉树图?
- 用Spring我可以做一个可选的路径变量吗?
- String.format()在Java中格式化双重格式
- com.jcraft.jsch.JSchException: UnknownHostKey
- Java中的操作符重载
- 如何加速gwt编译器?
- 在Hibernate中重新连接分离对象的正确方法是什么?
- 应该……接住环内还是环外?
- 如何格式化Joda-Time DateTime仅为mm/dd/yyyy?