近日在研究翟先生的《Spring Cloud微服务实战》,第三章在讲配置Eureka的时候,遇到了一个小问题。
前言
先上源代码:
Github: eureka-demo
问题重现
启动eureka-demo-server
启动eureka-demo-client
在浏览器中分别打开两个页面:
http://localhost:1234
和
http://localhost:8080
其截图如下:
以及
到这一步,可以看出来,Eureka的服务注册是成功的,但是如果我们做一个改动:
将eureka.client.controller.IndexController的:
// @Autowired // private DiscoveryClient client;
这两行注释还原,再运行eureka-demo-client,就会报错:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.netflix.discovery.DiscoveryClient] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE] ... 24 common frames omitted
大意就是说com.netflix.discovery.DiscoveryClient没有办法注入进去。
当然,书里说的”getLocalServiceInstance”这个方法也是找不到的。
解决办法
DiscoveryClient分两种:
一种是com.netflix.discovery.DiscoveryClient下的,它不是一个有效的Spring Bean类型
另一种是org.springframework.cloud.client.discovery.DiscoveryClient下的…
所以解决办法很简单了,换一个包下的DiscoveryClient就可以了