Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'ribbonService': Unsatisfied dependency expressed through field 'restTemplate': No qualifying bean of type [org.springframework.web.client.RestTemplate] found for dependency [org.springframework.web.client.RestTemplate]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.web.client.RestTemplate] found for dependency [org.springframework.web.client.RestTemplate]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

问题原因:

扫描路径是由@ComponentScan来指定的,默认为标注类当前包及当前包的子包。
也就是说,标注了@ComponentScan的启动类放在com.be.fallback包下面,只会扫描com.be.fallback包中的类,以及com.be.fallback.servlet、com.be.fallback.util等子包中的类,对于com.be.service等包中的类是不会扫描的。
注意事项一:很多人没有使用@ComponentScan,但是使用了@SpringBootApplication。@SpringBootApplication是通过内部封装@ComponentScan注解来实现实例扫描的,所以使用@SpringBootApplication也是一样的。

所以把以下代码放在启动类不会报错,但放在com.xxx.config包下的ConfigBean.java会报错。(com.xxx不是启动类所在的包名)

解决方法:

把包名com.xxx.config改成以启动类所在的包名(com.aaa)为前缀,即com.aaa.config
 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐