【问题标题】:Spring Boot: "No qualifying bean of type... found" when autowiring concrete classSpring Boot:自动装配具体类时“找不到类型的合格bean ...”
【发布时间】:2015-05-07 20:22:53
【问题描述】:

我正在使用 Spring Boot 和 Spring Boot JPA 编写组件。我有这样的设置:

界面:

public interface Something {
    // method definitions
}

实现:

@Component
public class SomethingImpl implements Something {
    // implementation
}

现在,我有一个使用 SpringJUnit4ClassRunner 运行的 JUnit 测试,我想用它来测试我的 SomethingImpl

当我这样做时

@Autowired
private Something _something;

它有效,但是

@Autowired
private SomethingImpl _something;

导致测试失败,抛出带有消息No qualifying bean of type [com.example.SomethingImpl] 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)}NoSuchBeanDefinitionException

但在测试用例中,我想显式地注入我的SomethingImpl,因为它是我要测试的类。我该如何做到这一点?

【问题讨论】:

    标签: java spring hibernate spring-mvc spring-boot


    【解决方案1】:

    如果你想要一个特殊的 bean,你必须使用 @Qualifier 注释:

    @Autowired
    @Qualifier("SomethingImpl")
    private Something _something;
    

    【讨论】:

    • 谢谢,这正是我需要的。还必须注意@Qualifier中的字符串必须像@Component("SomethingImpl")一样设置为@Component
    【解决方案2】:

    我发现你可以用 javax.inject 风格的 DI 做同样的事情:

    @Named("myConcreteThing")
    public class SomethingImpl implements Something { ... }
    

    你想注入的地方:

    @Inject
    @Named("myConcreteThing")
    private Something _something;
    

    @EnableAutoConfiguration@ComponentScan 正确拾取。

    【讨论】:

      【解决方案3】:

      我认为你需要在实现类中添加@Service .. 像

      @Service public class SomethingImpl implements Something { // implementation }

      【讨论】:

        【解决方案4】:

        我遇到了同样的问题,我可以通过将组件扫描路径添加到 Application 类来解决该问题 如下:

        @ComponentScan(basePackages= {"xx.xx"}) 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-09
          • 2018-06-12
          • 2019-06-14
          • 1970-01-01
          • 1970-01-01
          • 2020-01-31
          • 2017-09-07
          • 2017-04-29
          相关资源
          最近更新 更多