2012-09-27 42 views
1

我在代碼庫中發現了下面的非正統配置,這讓我很想知道。當我使用接口名稱作爲bean的名稱時,預期的Spring Context行爲是什麼?如果我在控制器中使用@Autowiring,它會有所作爲嗎?下面的代碼片段說明了這個設置:如果只控制器被定義爲將接口名稱也作爲bean名稱時的彈簧行爲?

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> 

或者,這將是預期的行爲:

class InfrastructureController { 
    @Autowired 
    public void setMyAppService(MyAppService svc){...} 
} 
+0

沒有shokes我你的代碼。 – Mik378

回答

2

爲什麼要這事嗎?你在xml中通過id引用bean,而不是通過接口類型。

<property name="myAppService" ref="myAppService"/>

這意味着名爲myAppService酒店將有注入ID myAppService豆。沒有關於接口。

編輯:如果您使用帶註釋的自動裝配,並且您有許多與組件註冊的相同接口的不同實現,那麼您必須使用qualifiers來告訴Spring您要使用哪種實現。如果您只註冊了一個實現,則不需要採取任何操作。

1

如果你把@Autowired唯有它按類型搜索的依賴(在你的情況下,它是MyAppService)。如果要縮小dependecy seaching可以如下使用@Qualifier:

class InfrastructureController { 
@Autowired 
@Qualifier("NAME_OF_BEAN") 
public void setMyAppService(MyAppService svc){...} 
} 
相關問題