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?
As long as there is only a single implementation of the interface and that implementation is annotated with
@Componentwith Spring’s component scan enabled, Spring framework can find out the (interface, implementation) pair. If component scan is not enabled, then you have to define the bean explicitly in your application-config.xml (or equivalent spring configuration file).Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the
@Qualifierannotation to inject the right implementation, along with@Autowiredannotation. If you are using @Resource (J2EE semantics), then you should specify the bean name using thenameattribute of this annotation.Firstly, it is always a good practice to code to interfaces in general. Secondly, in case of spring, you can inject any implementation at runtime. A typical use case is to inject mock implementation during testing stage.
Your bean configuration should look like this:
Alternatively, if you enabled component scan on the package where these are present, then you should qualify each class with
@Componentas follows:Then
workerinMyRunnerwill be injected with an instance of typeB.