'Spring: Why do we autowire the interface and not the implemented class?
Example
interface IA
{
public void someFunction();
}
@Resource(name="b")
class B implements IA
{
public void someFunction()
{
//busy code block
}
public void someBfunc()
{
//doing b things
}
}
@Resource(name="c")
class C implements IA
{
public void someFunction()
{
//busy code block
}
public void someCfunc()
{
//doing C things
}
}
class MyRunner
{
@Autowire
@Qualifier("b")
IA worker;
worker.someFunction();
}
Can someone explain this to me.
- How does spring know which polymorphic type to use.
- Do I need
@Qualifieror@Resource? - Why do we autowire the interface and not the implemented class?
Solution 1:[1]
Also it may cause some warnigs in logs like a Cglib2AopProxy Unable to proxy method. And many other reasons for this are described here Why always have single implementaion interfaces in service and dao layers?
Solution 2:[2]
It worked for me only when I declared following bean in my .XML configuration file because @Autowired is a post process
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"></bean>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sergey Ponomarev |
| Solution 2 | Harsh Patel |
