简体   繁体   中英

Spring: Cannot autowire a Bean which extends another Bean

I'd like to write a JUnit Test for a Dao class. The dao do not need any save method as it is reading only some data.

The Test is using HSQLDB and I need to insert some test data first. As I do not want to write code only to make the test running I extend the DaoImpl class to have a save method.

Now I'd like to @Autowire the DaoTestImpl class but getting a No qualifying bean of type […] found for dependency error.

My setup in src/main looks like this:

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

And for the test in src/test I have the new class:

@Repository("DaoTestImpl") class DaoTestImpl extends DaoImpl

In the JUnit Test I'm using

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

Is there something wrong when autowireing a Bean which extends another Bean? If the DaoTestImpl class is implementing the interface Spring will find the proper Bean. But in this case I cannot test the DaoImpl class.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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