这篇文章主要介绍了SpringCloud假装参数问题及解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
今天遇到使用假装调用微服务,传递参数时遇到几个问题
1。无参数
以得到方式请求
服务提供者
@RequestMapping (“/hello”) 公共字符串Hello () { 返回“你好,提供者”; }
服务消费者
@GetMapping (“/hello”)字符串hello ();
2。单个参数
(1)得到,@PathVariable
服务提供者
@GetMapping(“/测试/{名称}”) 公共字符串测试(@PathVariable字符串名称){ 返回“你好,”+名称; }
服务消费者
@GetMapping(“/测试/{名称}”) 字符串测试(@PathVariable(“名字”)字符串名称);
(2)得到,@RequestParam
服务提供者
@RequestMapping(“/测试”) 公共测试字符串(字符串名称){返回“你好,”+名称; }
服务消费者
@RequestMapping(“/测试”) 字符串测试(@RequestParam字符串名称);
会遇到报错
RequestParam.value()是空> @RequestMapping(“/测试”) 字符串测试(@RequestParam(“名字”)字符串名称);
(3)文章
@RequestBody
不需要注解的描述
@RequestMapping(“/测试”) 字符串测试(@RequestBody字符串名称);注:
-
<李>参数前使用了@RequestBody注解的,都以发布方式消费服务李>
<李> @RequestBody注解的参数,需要发布方式才能传递数据李>
2.假装多参数的问题
(1)得到,@PathVariable
服务提供者
@GetMapping(“/测试/{名称}/{xyz}”) 公共字符串测试(@PathVariable字符串名称,@PathVariable字符串xyz) { 返回“你好,”+名字+”、“+ xyz; }
服务消费者
@GetMapping(“/测试/{名称}/{xyz}”) 字符串测试(@PathVariable(“名字”)字符串名称,@PathVariable (“xyz”)字符串xyz);
(1)得到,@RequestParam
服务提供者
@RequestMapping(“/测试”) 公共测试字符串(字符串名称,整数类型){ 如果(type==1) { 返回“你好,”+名称; 其他}{ 返回“你好,提供者——“+名称; } }
服务消费者
@RequestMapping(“/测试”) 字符串测试(字符串名称,整数类型);
会遇到报错方法有太多身体参数
说明:
如果服务消费者传过来参数时,全都用的是@RequestParam的话,那么服务提供者的控制器中对应参数前可以写@RequestParam,也可以不写
服务消费者假装调用时,在所有参数前加上@RequestParam注解
正确的写法
@RequestMapping(“/测试”) 字符串测试(@RequestParam(“名字”)字符串名称,@RequestParam(“类型”)整数类型),
(2)文章
如果接收方不变
服务消费者
@RequestMapping(“/测试”) 字符串测试(@RequestBody字符串名称,@RequestBody整数类型),
会遇到报错方法有太多身体参数
服务消费者为
@RequestMapping(“/测试”) 字符串测试(@RequestBody字符串名称,@RequestParam(“类型”)整数类型),
名称的值会为空
说明:
如果服务消费者传过来参数,有@RequestBody的话,那么服务提供者的控制器中对应参数前必须要写@RequestBody
正确的写法
服务提供者
@RequestMapping(“/测试”) 公共字符串测试(@RequestBody字符串名称,整数类型){ 如果(type==1) { 返回“你好,”+名称; 其他}{ 返回“你好,提供者——“+名称; } }SpringCloud假装参数问题及解决方法