spring 依賴注入到直接new 對象


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

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

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

 1 package net.blogjava.chenlb;
 2 
 3 import org.springframework.beans.BeansException;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.context.ApplicationContextAware;
 6 
 7 /**
 8  * 此類可以取得Spring的上下文.
 9  * Spring 使new方法創建的對象可以引用spring管理的bean.
10  * 2007-10-18 上午11:12:33
11  * @author chenlb
12  */
13 public class SpringContext implements ApplicationContextAware {
14 
15     protected static ApplicationContext context;
16     
17     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
18         context = applicationContext;
19     }
20 
21     public static ApplicationContext getContext() {
22         return context;
23     }
24 
25 }

2.然后在spring配置文件里加

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

3.其它類中引用

 

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

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

 1 package net.blogjava.chenlb;
 2 
 3 public class MyServerFactory {
 4 
 5 
 6     public static MyBean1 getMyBean1() {
 7         return (MyBean1) SpringContext.getContext().getBean("myBean1");
 8     }
 9     
10 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM