日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

spring 依賴注入到直接new 對象

系統 2345 0

????? 當為遺留系統加入spring時,經典問題就是遺留系統需要引用spring管理的bean。幸好spring有機制可以處理這些。

建一個類實現ApplicationContextAware接口,有一個引用ApplicationContext的靜態成員,然后,遺留系統需要引用spring管理的bean的地方,使用這個類。

1.比如:我這里建一個SpringContext類

package ?net.blogjava.chenlb;

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配置文件里加

< bean? id ="springContext" ?class ="net.blogjava.chenlb.SpringContext" ></ bean >


3.其它類中引用

MyBean?myBean? = ?(MyBean)?SpringContext.getContext().getBean( " myBean " );


4.如果老是寫SpringContext.getContext().getBean("...");麻煩,可以建一個工廠類來返回你要的bean

package ?net.blogjava.chenlb;



public ? class ?MyServerFactory?{


????
public ? static ?MyBean1?getMyBean1()?{
????????
return ?(MyBean1)?SpringContext.getContext().getBean( " myBean1 " );
????}
????

}

spring 依賴注入到直接new 對象


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

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

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦?。?!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 沙河市| 大厂| 长阳| 鄂尔多斯市| 衡水市| 安多县| 富顺县| 十堰市| 安阳市| 民权县| 静乐县| 富平县| 郓城县| 迭部县| 五河县| 曲周县| 镇江市| 名山县| 吴忠市| 曲沃县| 濮阳县| 海南省| 剑川县| 调兵山市| 广州市| 汉阴县| 嘉义县| 绥滨县| 贡山| 潞城市| 涿鹿县| 化隆| 阿克苏市| 锡林郭勒盟| 太和县| 青田县| 读书| 聂荣县| 新沂市| 临洮县| 万年县|