2 回答

TA貢獻1891條經驗 獲得超3個贊
spring如何知道要使用哪種多態類型。
只要接口只有一個實現,并且該實現在@Component啟用了Spring的組件掃描的情況下進行注釋,Spring框架就可以找出(接口,實現)對。如果未啟用組件掃描,則必須在application-config.xml(或等效的spring配置文件)中顯式定義Bean。
我需要@Qualifier或@Resource嗎?
一旦擁有多個實現,就需要對每個實現進行限定,并且在自動裝配期間,需要使用@Qualifier注釋將正確的實現以及@Autowired注釋注入。如果使用@Resource(J2EE語義),則應使用name此批注的屬性指定Bean名稱。
為什么我們要對接口而不是已實現的類進行自動裝配?
首先,一般來說,對接口進行編碼始終是一個好習慣。其次,在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配置應如下所示:
<bean id="b" class="B" />
<bean id="c" class="C" />
<bean id="runner" class="MyRunner" />
或者,如果在存在這些組件的軟件包上啟用了組件掃描,則應按以下步驟對每個類別進行限定@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();
}
然后worker在MyRunner中將注入type的實例B。
添加回答
舉報