我在一些Spring Reactive示例中看到,使用@GetMapping代替@RequestMapping。
@GetMapping
是一个组合注解,作为@RequestMapping(method = RequestMethod.GET)
的快捷方式。
@GetMapping
是较新的注解。它支持消费(consumes)选项。
消费选项包括:
consumes = "text/plain"
consumes = {"text/plain", "application/*"}
更多详情请参见: GetMapping Annotation
RequestMapping也支持消费选项。
@GetMapping
只能应用于方法级别,而@RequestMapping
注解可以应用于类级别和方法级别。
正如您可以在这里看到的:
@GetMapping
是一个组合注释,作为@RequestMapping(method = RequestMethod.GET)
的快捷方式。
@GetMapping
和@RequestMapping
之间的区别在于:
@GetMapping
像@RequestMapping
一样支持consumes
属性。
@RequestMapping
是类级别的
@GetMapping
是方法级别的
从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) 的快捷方式。
更多阅读:
RequestMapping
可以在类级别使用:
该注释既可以在类级别,也可以在方法级别使用。在大多数情况下,在方法级别应用程序将倾向于使用特定于HTTP方法的变体 @GetMapping、@PostMapping、@PutMapping、@DeleteMapping 或 @PatchMapping 之一。
而GetMapping
仅适用于方法:
映射 HTTP GET 请求到特定的处理程序方法的注释。
`@RequestMapping` since 2.5
=> 可处理所有 HTTP 方法
=> 适用于类和方法
=> 如果我们将其与 @Component
一起使用,可以将其用作 @Controller
和 @RestController
的替代品。
`@GetMapping` since 4.3
=> 只能处理HTTP的GET方法
=> 仅适用于方法
@GetMapping
是 @RequestMapping(method = RequestMethod.GET)
的一种特定类型。两者都支持consumes属性。
@GetMapping是@ RequestMapping(method = RequestMethod.GET)的快捷方式
@RequestMapping是类级别的
@GetMapping是方法级别的
4) @RequestMapping注释用于将Web请求映射到特定的处理程序类和函数。此注释的主要优点是它可以用于控制器类和方法。
5)在控制器方法上声明@RequestMapping时,建议具体说明,因为在大多数映射处理程序类中,不使用@Getmapping。
@RequestMapping
支持 consumes,即使 method=GET,而 @GetMapping 不支持 consumes。除此之外,@GetMapping 与 @RequestMapping(method=RequestMethod.GET) 相同。