SpringBoot 中常用注解及各种注解作用

时间:2021-05-20

本篇文章将介绍几种SpringBoot 中常用注解

其中,各注解的作用为:

@PathVaribale 获取url中的数据

@RequestParam 获取请求参数的值

@GetMapping 组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写

@RestController是@ResponseBody和@Controller的组合注解。

@PathVaribale 获取url中的数据

看一个例子,如果我们需要获取Url=localhost:8080/hello/id中的id值,实现代码如下:

@RestControllerpublic class HelloController { @RequestMapping(value="/hello/{id}",method= RequestMethod.GET) public String sayHello(@PathVariable("id") Integer id){ return "id:"+id; }}

@RequestParam 获取请求参数的值

直接看一个例子,如下

@RestControllerpublic class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String sayHello(@RequestParam("id") Integer id){ return "id:"+id; }}

在浏览器中输入地址:localhost:8080/hello?id=1000,可以看到如下的结果:

当我们在浏览器中输入地址:localhost:8080/hello?id ,即不输入id的具体值,此时返回的结果为null。具体测试结果如下:

@GetMapping 组合注解

@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。该注解将HTTP Get 映射到 特定的处理方法上。

即可以使用@GetMapping(value = “/hello”)来代替@RequestMapping(value=”/hello”,method= RequestMethod.GET)。即可以让我们精简代码。

例子

@RestControllerpublic class HelloController { //@RequestMapping(value="/hello",method= RequestMethod.GET) @GetMapping(value = "/hello") //required=false 表示url中可以不穿入id参数,此时就使用默认参数 public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){ return "id:"+id; }}

@RestController

Spring4之后新加入的注解,原来返回json需要@ResponseBody和@Controller配合。

即@RestController是@ResponseBody和@Controller的组合注解。

@RestControllerpublic class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String sayHello(){ return "hello"; }}

与下面的代码作用一样

@Controller@ResponseBodypublic class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String sayHello(){ return "hello"; }}

注解@RequestParam 和 @PathVarible的区别

@RequestParam是请求中的参数。如get?id=1

@PathVarible是请求路径中的变量如 get/id=1

总结

以上所述是小编给大家介绍的SpringBoot 中常用注解及各种注解作用,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章