【问题标题】:Unsatisfied dependency expressed through field 'fooService': No qualifying bean of type [aaa.FooService] found for dependency [aaa.FooService]通过字段 'fooService' 表示的不满足依赖项:没有为依赖项 [aaa.FooService] 找到类型为 [aaa.FooService] 的合格 bean
【发布时间】:2016-12-08 18:22:37
【问题描述】:

我在 Spring boot 1.4.0 中遇到过这种 Spring 的奇怪行为。 Spring 基本上告诉我它不能将 bean 自动装配到资源,因为它没有发现自己的依赖关系。

UnsatisfiedDependencyException: Error creating bean with name 'restResource': Unsatisfied dependency expressed through field 
'fooService': No qualifying bean of type [**aaa.FooService**] found for dependency [**aaa.FooService**]

FooService 在资源中自动装配。当我将它@Autowire 到创建资源的@Configuration 文件中时,它会按预期注入那里。

这行得通:

public class ServiceMocksRestConfig extends WebMvcConfigurerAdapter {
@Autowired
private FooService fooService; //instance here

@Bean
public FooResource fooResource() {
    return new FooResource(); // debuger stop here
}

//调试器步入

@RestController
public class FooResource {
    @Autowired
    private FooService fooService; //bang

有人知道,可能出了什么问题吗?

有趣的是,当我使用 boot spring runner 从测试中运行应用程序时,它也可以工作(一切,包括这个资源)

【问题讨论】:

    标签: java spring spring-mvc spring-boot dependency-injection


    【解决方案1】:

    我今天设法找到了根本原因。它的 Spring Boot devtools - 更准确地说是它的拆分类加载器(相关错误:https://github.com/spring-projects/spring-boot/issues/3316

    当我在子 REST @Configuration 即将 @Autowire FooService 时在 ListableBeanFactory 中放置断点时

    FooService instanceof FooServiceInterface,它返回 false。 当我做了 FooService.class.getClassLoader() 和 beanfactory.getBean("fooService" /cannot use class here, will tr​​igger not found exception/).getClass().getClassloader() 这些是不同的(一个是 AppClassLoader,另一个是 devtools 可重启的类加载器)。

    解决方案:从类路径中删除引导开发工具。

    【讨论】:

      【解决方案2】:

      这样做的确切原因是,在运行时尝试将 FooService 自动装配到 ServiceMocksRestConfig 时,Spring IOC 容器内没有为 FooService 类型初始化的 bean。

      这可能是由开发中的不同错误引起的。这个article 解决了所有可能导致此问题的错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-29
        • 2016-12-31
        • 2018-12-02
        • 2016-12-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多