前几天我在我的代码库中发现了以下非正统的配置,这让我很奇怪。当我将接口(interface)名称也用作 bean 名称时,预期的 Spring Context 行为是什么?如果我在 Controller 中使用@Autowiring 会有什么不同吗?以下代码段说明了此设置:
interface MyAppService {...}
class InfrastructureService implements MyAppService {...}
class AdministrationService implements MyAppService {...}
class InfrastructureController {
// some code
public void setMyAppService(MyAppService svc){...}
}
<bean id="myAppService" class="InfrastructureService"/>
<bean id="administrationService" class="AdministrationService"/>
<bean id="infrastructureController" class="InfrastructureController">
<property name="myAppService" ref="myAppService"/>
</bean>
或者,如果只将 Controller 定义为:
class InfrastructureController {
@Autowired
public void setMyAppService(MyAppService svc){...}
}
最佳答案
为什么这里很重要?您通过 id
引用 beans在 xml 中,而不是按接口(interface)类型。
<property name="myAppService" ref="myAppService"/>
这意味着名为 myAppService
的属性将拥有 ID 为 myAppService
的 bean注入(inject)。与接口(interface)无关。
编辑:如果你使用带有注解的 Autowiring ,并且你有许多不同的相同接口(interface)的实现注册为组件,那么你必须使用 qualifiers
告诉Spring
你要使用哪个实现。如果您只注册了一个实现,则无需执行任何操作。
关于java - 将接口(interface)名称也用作 bean 名称时的 Spring 行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12620872/