我是跟着尚硅谷的SpringCloud教程学的,然后在写代码的时候用了比较新的版本去替代视频里的教学版本。
这个问题出现在引入feign组件的时候。
使用SpringCloud的Finchley.SR1版本
引用openfeign替代了 feign,原因如下
链接地址https://stackoverflow.com/questions/49823158/differences-between-netflix-feign-openfeign
大意是说feign是旧版本,16年就不再更新了,现在SpringCloud使用openfein去替代feign
1,在公用service接口层实现@FeignClient注解
@FeignClient(value = "MICROSERVICECLOUD-DEPT")
public interface DeptClientService
{
@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
public Dept get(@PathVariable("id") long id);
@RequestMapping(value = "/dept/list", method = RequestMethod.GET)
public List<Dept> list();
@RequestMapping(value = "/dept/add", method = RequestMethod.POST)
public boolean add(Dept dept);
}
然后执行maven 的 clean 和 install,供其他模块调用
2,在feign模块的controller层调用
@RestController
public class DeptController_Consumer
{
@Autowired
private DeptClientService service;
@RequestMapping(value = "/consumer/dept/get/{id}")
public Dept get(@PathVariable("id") Long id)
{
return this.service.get(id);
}
@RequestMapping(value = "/consumer/dept/list")
public List<Dept> list()
{
return this.service.list();
}
@RequestMapping(value = "/consumer/dept/add")
public Object add(Dept dept)
{
return this.service.add(dept);
}
}
此时IDEA针对service报错:Could not autowire. No beans of 'DeptClientService' type found. less... (⌘F1)
Inspection info:Checks autowiring problems in a bean class.
这里报错不影响代码执行,但是我没理解深层原因。按说正常调用@Autowired
不会报错。
feign主启动类类如下
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages= {"com.atguigu.spring.microservicecloudconsumerdeptfeign"})
@ComponentScan("com.atguigu.spring.microservicecloudconsumerdeptfeign")
public class MicroservicecloudConsumerDeptFeignApplication {
public static void main(String[] args) {
SpringApplication.run(MicroservicecloudConsumerDeptFeignApplication.class, args);
}
}
注解@ComponentScan报红,提示@SpringBootApplication注解已经扫描过该包,但不影响程序运行
启动之后直接挂掉,报错提示如下
Description:
Field service in com.atguigu.spring.microservicecloudconsumerdeptfeign.controller.DeptController_Consumer required a bean of type 'com.atguigu.spring.microservicecloudapi.service.DeptClientService' that could not be found.
Action:
Consider defining a bean of type 'com.atguigu.spring.microservicecloudapi.service.DeptClientService' in your configuration.
应该是service没有注入进去,找不到。
这个阶段我还分析不了原因,所以搜了一下,找到一个可能的解决方式
链接https://stackoverflow.com/questions/30241198/error-injecting-feignclient-from-another-project
于是把主启动类注解改成
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages= {"com.atguigu.spring.microservicecloudapi.service","com.atguigu.spring.microservicecloudconsumerdeptfeign"})
public class MicroservicecloudConsumerDeptFeignApplication {
public static void main(String[] args) {
SpringApplication.run(MicroservicecloudConsumerDeptFeignApplication.class, args);
}
}
项目正常启动,访问正常