springcloud 使用feign建立client介面 ,controller引入後報依賴錯誤 Unsatisfied dependency
阿新 • • 發佈:2020-11-21
如題所示,程式碼如下
1 -- 1. client 2 @FeignClient(name="microservice-provider-user") 3 public interface UserFeignClient { 4 @GetMapping("/users/{id}") 5 User findById(@PathVariable Long id); 6 } 7 8 -- 2. 控制層 9 @RequestMapping("/movies") 10 @RestController 11 public class MovieController { 12 @Autowired13 private RestTemplate restTemplate; 14 15 @Autowired 16 private UserFeignClient userFeignClient; 17 18 @GetMapping("/users/{id}") 19 public User findById(@PathVariable Long id) { 20 // 這裡用到了RestTemplate的佔位符能力 21 User user = userFeignClient.findById(id); 22 //...電影微服務的業務... 23 return user; 24 } 25 } 26 27 -- 3. 啟動類 28 @SpringBootApplication 29 @EnableEurekaClient 30 @EnableFeignClients("com.caiya.movie.utils") 31 public class FeignMovieApplication { 32 @Bean 33 public RestTemplate restTemplate() { 34 return new RestTemplate();35 } 36 37 public static void main(String[] args) { 38 SpringApplication.run(FeignMovieApplication.class, args); 39 } 40 }
百度了下,得到的結果是
1. springboot 啟動類註解 @EnableFeignClients 沒有寫掃描包 (對比筆者自己的工程,client是在 啟動類所在包的子包下,理論上不是這個問題
不過還是按提示修改後,一樣報錯...
2. 筆者自己設定了多個模組,包名存在一致的情況,為了排除這個情況導致,修改包名後還是一樣的問題
最終解決方案:
還是 stackoverflow 牛皮,google一下就出來答案了
原因是我在複製網上教程時候,直接把
解答原文及地址: https://stackoverflow.com/questions/49415197/spring-boot-2-unsatisfied-dependency-on-feign-client-when-autowired-for-servic There was an issue in feign client before. I guess you are experiencing the same maybe because you are using an old version but what you should do is including the pathVariable name in your @PathVariable annotation like this @RequestMapping(value = "/hello/{name}", method = RequestMethod.GET) String hello(@PathVariable(value = "name") String name); You can find the details from https://github.com/spring-cloud/spring-cloud-netflix/issues/861