當存在多個候選者時選擇特定的bean由@Qualifier
解決。只需在應用程序上下文中聲明相同的bean併爲它們分配不同的id或限定符名稱即可。讓我們來看看這個類:
public class Foo{
@Autowired
private SessionFactory sessionFactory;
}
假設都SessionFactoryImpl1
和SessionFactoryImpl2
都是候選人豆線,你想點SessionFactory來SessionFactoryImpl1
實例,而不是,那麼你需要添加@Qualifier
註釋就像在下面的例子:
public class Foo{
@Autowired
@Qualifier("sessionFactory1")
private SessionFactory sessionFactory;
}
而在你的應用程序上下文
<bean class="example.SessionFactoryImpl1">
<qualifier value="sessionFactory1"/>
<!-- inject any dependencies required by this bean -->
</bean>
<bean class="example.SessionFactoryImpl2">
<qualifier value="sessionFactory2"/>
<!-- inject any dependencies required by this bean -->
</bean>
來源
2013-04-12 02:33:49
cRx
這可以爲SM工作所有的應用程序,但不是當你有代碼行的人。 SessionFactory就是一個例子,會有更多。難道沒有辦法告訴Spring特定的一組類(一個給定jar中的所有東西)應該有一個獨立的上下文嗎? – mabn
你的意思是說我可以在註釋庫代碼上強制使用限定符? 這種歧義正是我爲什麼不用@Autowired註釋庫代碼的原因。你不知道如何使用這個bean –
@ChristianBongiorno你會分享你的策略來處理使用bean的庫代碼嗎?如果你不註釋庫代碼,那麼你如何進行佈線? – Stephane