[英]Can I change the implementation class injected by spring in runtime?
我有一個類已在spring之前注入到applicationContext.xml上,我需要在不更改applicationContext.xml的情況下更改該實現。
我聽說過AOP“ IntroductionInterceptor”,但沒有發現很多有用的結果。
有人可以幫助我嗎?
PS。 對不起,我英語不好,希望能給理解。
解決的方法之一是應用服務定位器模式 。 代替直接注入bean,可以注入ServiceLocator,它可以返回不同的實現。
//ServiceLocator bean
public Class ServiceLocator {
@Resource(name="service1")
private Service service1;
@Resource(name="service1")
private Service Service2;
public Service getService(String service) {
return ... //service
}
}
您可以通過多種方式進行操作,以下幾種方式:
編寫一個xml文件,通過添加相同的bean id和要使用的實現類來覆蓋配置,然后將這個新的xml導入到您現有的應用程序上下文中。
通過代碼,您可以根據需要在調用代碼之前設置新的實現。
可能會有更多,但大多數情況下,我們在項目數量中使用了“ 1”。
如果您有多個具有相同id的bean,spring將會獲取最新的id,例如
<beans>
<import resource="a.xml"/>
<import resource="b.xml"/>
</beans>
現在,如果a.xml
和b.xml
都具有使用相同ID定義的bean,spring將使用b.xml
定義的bean。
干杯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.