could not autowire field: private com.netflix.discovery.DiscoveryClient

本贴最后更新于 2238 天前,其中的信息可能已经时过境迁

近日在研究翟先生的《Spring Cloud 微服务实战》,第三章在讲配置 Eureka 的时候,遇到了一个小问题。

前言

先上源代码:

Github: eureka-demo

问题重现

  • 启动 eureka-demo-server

  • 启动 eureka-demo-client

  • 在浏览器中分别打开两个页面:

      http://localhost:1234
    

      	http://localhost:8080
    

    其截图如下:

    euraka

    以及

  • 到这一步,可以看出来,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"这个方法也是找不到的。

error

解决办法

DiscoveryClient 分两种:

  • 一种是 com.netflix.discovery.DiscoveryClient 下的,它不是一个有效的 Spring Bean 类型

  • 另一种是 org.springframework.cloud.client.discovery.DiscoveryClient 下的...

所以解决办法很简单了,换一个包下的 DiscoveryClient 就可以了

  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3167 引用 • 8207 回帖 • 1 关注
  • Spring

    Spring 是一个开源框架,是于 2003 年兴起的一个轻量级的 Java 开发框架,由 Rod Johnson 在其著作《Expert One-On-One J2EE Development and Design》中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 JavaEE 应用程序开发提供集成的框架。

    940 引用 • 1458 回帖 • 157 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...