@RequestMapping和@GetMapping @PostMapping 区别

您所在的位置:网站首页 @getmapping注解的作用 @RequestMapping和@GetMapping @PostMapping 区别

@RequestMapping和@GetMapping @PostMapping 区别

2024-01-21 04:56| 来源: 网络整理| 查看: 265

       最近学习看一些代码,发现对于发送请求这件事,有的地方用@RequestMapping,有的地方用@PostMapping,为了搞清楚区别,特意查了下spring 源代码,现在特此记录下。

 @GetMapping用于将HTTP get请求映射到特定处理程序的方法注解 具体来说,@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。

@PostMapping用于将HTTP post请求映射到特定处理程序的方法注解 具体来说,@PostMapping是一个组合注解,是@RequestMapping(method = RequestMethod.POST)的缩写。

下面我们来看下@GetMapping的源码,可以对上面的两句释义给予充分的支撑。

/** * Annotation for mapping HTTP {@code GET} requests onto specific handler * methods. * *

Specifically, {@code @GetMapping} is a composed annotation that * acts as a shortcut for {@code @RequestMapping(method = RequestMethod.GET)}. * * * @author Sam Brannen * @since 4.3 * @see PostMapping * @see PutMapping * @see DeleteMapping * @see PatchMapping * @see RequestMapping */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented @RequestMapping(method = RequestMethod.GET) public @interface GetMapping { /** * Alias for {@link RequestMapping#name}. */ @AliasFor(annotation = RequestMapping.class) String name() default ""; ... }

上面代码中,最关键的是 @RequestMapping(method = RequestMethod.GET),这行代码即说明@GetMapping就是@RequestMapping附加了请求方法。同时,可以看到@GetMapping这个注解 是spring4.3版本引入,同时引入的还有@PostMapping、@PutMapping、@DeleteMapping和@PatchMapping,一共5个注解。

所以,一般情况下用@RequestMapping(method = RequestMethod. XXXX)即可。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3