java - 将接口(interface)名称也用作 bean 名称时的 Spring 行为?

标签 java spring

前几天我在我的代码库中发现了以下非正统的配置,这让我很奇怪。当我将接口(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/

相关文章:

java - websocket.send 期间收到 "InvalidStateError: DOM Exception 11"

Spring Data JPA Java 配置 HibernatePersistence.class

java - JSF EJB3 到 Spring 3,BigInteger 始终为 0 而不是 null

java - Spring boot with testcontainers - 如何防止上下文重新加载时数据库初始化

java - 在测试中使用 Spring JpaRepository

java - 将友谊保存在数据库中。社交网络服务

java - 如何在 servlet 上设置内容类型

java - 清理 ThreadPoolExecutor 中的有界队列

java - 无法解析符号 'MODE_PRIVATE'

java - 属性文件字符串长度限制(JAVA)