springCloud使用feign远程调用服务注入映射接口失败
在一次项目中,使用feign远程调用服务时,发现feign的映射接口一直注入容器失败
映射接口
package com.jn.feign.api;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient("RIBBON-PROVIDER")
@RequestMapping(value = "/provider")
public interface IProviderClient {
@RequestMapping("/test1")
String test1();
//
// //方法接收多个参数
@RequestMapping("/login")
String login(@RequestParam("username") String username, @RequestParam("password") String password);
//
// //方法接收对象
@RequestMapping("/addUserFrom")
String addUserFrom(User user);
// //方法接收JSON数据
@RequestMapping("/addUserJson")
String addUserJson(@RequestBody User user);
//
// //restful风格
@RequestMapping("/getUserById/{id}")
String getUserByID(@PathVariable Integer id);
}
主启动类
@SpringBootApplication
@ComponentScan("com.jn")
@EnableEurekaClient
@EnableFeignClients("com.jn.feign.api")//开启feign机制,并指定映射接口路径
public class Day0111SpringcloudFeignConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(Day0111SpringcloudFeignConsumerApplication.class, args);
}
}
调用的controller
@RestController
@RequestMapping("/feign")
public class FeignController {
@Autowired
IProviderClient client;
@GetMapping("/test")
public String test(){
String s = client.test1();
return s;
}
}
启动后报错信息
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'feignController': Unsatisfied dependency expressed through field 'client'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.qf.feign.api.IProviderClient': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateException: PathVariable annotation was empty on param 0.
eureka服务器也确定RIBBON-PROVIDER已经注册上去了,最终在检查下发现了映射接口使用restful风格调用的时候@PathVariable没有指定参数的id
修改后
在使用feign携带参数远程调用服务的时候,一定要指定参数名,它不能像springMVC一样将形参自动的作为参数值,需要自己手动指定