简体   繁体   English

春季:无法自动装配扩展了另一个Bean的Bean

[英]Spring: Cannot autowire a Bean which extends another Bean

I'd like to write a JUnit Test for a Dao class. 我想为Dao类编写一个JUnit测试。 The dao do not need any save method as it is reading only some data. dao不需要任何保存方法,因为它仅读取一些数据。

The Test is using HSQLDB and I need to insert some test data first. 测试正在使用HSQLDB,我需要先插入一些测试数据。 As I do not want to write code only to make the test running I extend the DaoImpl class to have a save method. 因为我不想只编写代码来使测试运行,所以我将DaoImpl类扩展为具有save方法。

Now I'd like to @Autowire the DaoTestImpl class but getting a No qualifying bean of type […] found for dependency error. 现在,我想@Autowire DaoTestImpl类,但发现类型为[…]No合格bean因依赖性错误出现。

My setup in src/main looks like this: 我在src / main中的设置如下所示:

interface Dao ...
@Repository("Dao") class DaoImpl implements Dao ...

And for the test in src/test I have the new class: 对于src / test中的测试,我有了新类:

@Repository("DaoTestImpl") class DaoTestImpl extends DaoImpl

In the JUnit Test I'm using 在JUnit测试中,我正在使用

@Autowired
@Qualifier("DaoTestImpl")
private DaoTestImpl daoTestImpl;

Is there something wrong when autowireing a Bean which extends another Bean? 自动接线扩展另一个Bean的Bean时出现问题吗? If the DaoTestImpl class is implementing the interface Spring will find the proper Bean. 如果DaoTestImpl类正在实现接口,Spring将找到合适的Bean。 But in this case I cannot test the DaoImpl class. 但是在这种情况下,我无法测试DaoImpl类。

You need to declare the interface as a field and add qualifier using the name of the implemented class. 您需要将接口声明为字段,并使用实现的类的名称添加限定符。 Then it will autowire as expected. 然后它将按预期自动布线。 The code will look like as bellow : 该代码将如下所示:

@Autowired
@Qualifier("daoTestImpl")
// The interface
private Dao dao;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM