How does spring know which polymorphic type to use.
只要只有一个接口的实现,并且实现使用@Component注释,并且启用了Spring的组件扫描,Spring框架就可以找到(接口,实现)对。如果未启用组件扫描,则必须在application-config.xml(或等效的spring配置文件)中显式地定义bean。
Do I need @Qualifier or @Resource?
一旦你有多个实现,那么你需要对每个实现进行限定,并且在自动布线期间,您需要使用@Qualifier注释注入正确的实现以及@Autowired注释。如果使用@Resource(J2EE语义),那么应该使用此注释的name属性指定bean名称。
Why do we autowire the interface and not the implemented class?
首先,对于一般的接口编码总是一个好的做法。其次,在spring的情况下,可以在运行时注入任何实现。一个典型的用例是在测试阶段注入模拟实现。
interface IA
{
public void someFunction();
}
class B implements IA
{
public void someFunction()
{
//busy code block
}
public void someBfunc()
{
//doing b things
}
}
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();
}
你的bean配置应该是这样:
或者,如果在包含这些组件的程序包上启用了组件扫描,则应该使用@Component限定每个类,如下所示:
interface IA
{
public void someFunction();
}
@Component(value="b")
class B implements IA
{
public void someFunction()
{
//busy code block
}
public void someBfunc()
{
//doing b things
}
}
@Component(value="c")
class C implements IA
{
public void someFunction()
{
//busy code block
}
public void someCfunc()
{
//doing C things
}
}
@Component
class MyRunner
{
@Autowire
@Qualifier("b")
IA worker;
....
worker.someFunction();
}
然后,MyRunner中的worker将注入一个类型为B的实例。