java 接口互相连接_java – Spring:为什么我们自动连接接口而不是实现类?

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的实例。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值