????? 當為遺留系統加入spring時,經典問題就是遺留系統需要引用spring管理的bean。幸好spring有機制可以處理這些。
建一個類實現ApplicationContextAware接口,有一個引用ApplicationContext的靜態成員,然后,遺留系統需要引用spring管理的bean的地方,使用這個類。
1.比如:我這里建一個SpringContext類
import ?org.springframework.beans.BeansException;
import ?org.springframework.context.ApplicationContext;
import ?org.springframework.context.ApplicationContextAware;
/**
?*?此類可以取得Spring的上下文.
?*?Spring?使new方法創建的對象可以引用spring管理的bean.
?*?2007-10-18?上午11:12:33
?*? @author ?chenlb
? */
public ? class ?SpringContext? implements ?ApplicationContextAware?{
???? protected ? static ?ApplicationContext?context;
????
???? public ? void ?setApplicationContext(ApplicationContext?applicationContext)? throws ?BeansException?{
????????context? = ?applicationContext;
????}
???? public ? static ?ApplicationContext?getContext()?{
???????? return ?context;
????}
}
2.然后在spring配置文件里加
3.其它類中引用

4.如果老是寫SpringContext.getContext().getBean("...");麻煩,可以建一個工廠類來返回你要的bean
public ? class ?MyServerFactory?{
???? public ? static ?MyBean1?getMyBean1()?{
???????? return ?(MyBean1)?SpringContext.getContext().getBean( " myBean1 " );
????}
????
}
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
