4

I have this super class:

@Component
public class DAOBase {
}

this other one class extends DAOBase

@Component
public class VoceDAO extends DAOBase{       
}

When I AutoWired the class DAOBase this way

@Service
public class TransactionService {
    @Autowired
    private DAOBase dAOBase;
}

I get this error:

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.jeansedizioni.dao.DAOBase] is defined: expected single matching bean but found 2: DAOBase,voceDAO
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:865)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
    ... 37 more

Reading some posts I found this solution:

@Component("DAOBaseBeanName")
public class DAOBase {
}

I want to be sure I perfectly understood the solution. With @Component("DAOBaseBeanName") I give the class DAOBase the specific name "DAOBaseBeanName", with which the application can identify the class DAOBase, in order not to mix it up with other classes that extend DAOBase. Is it right?

Thank you.

MDP
  • 4,177
  • 21
  • 63
  • 119
  • 1
    IMHO your `DAOBase` should be `abstract` and not have a `@Component` annotation... Next to that you should be using the concrete type `VoceDao` in your service and not the base class. – M. Deinum Jan 08 '16 at 08:31

3 Answers3

4

Try to add @Qualifier annotation like this:

 @Autowired
 @Qualifier("dAOBase")
 private DAOBase dAOBase;

To specify which bean you want to inject in your class (DAOBase or voceDAO).

Abdelhak
  • 8,299
  • 4
  • 22
  • 36
1

The reason why @Resource(name = "{your child class name}") works but @Autowired sometimes don't work is because of the difference of their Matching sequence

Matching sequence of @Autowire
Type, Qualifier, Name

Matching sequence of @Resource
Name, Type, Qualifier

The more detail explanation can be found here:
Inject and Resource and Autowired annotations

In this case, different child class inherited from the parent class or interface confuses @Autowire, because they are from same type; As @Resource use Name as first matching priority , it works.

RAY
  • 2,201
  • 2
  • 19
  • 18
0

Yes it is as you have written. You can also specify which implementation to inject when you are autowiring a bean using Qualifier annotation.

Mateusz Dryzek
  • 651
  • 4
  • 18