隨筆-153  評論-235  文章-19  trackbacks-0
                當為遺留系統(tǒng)加入spring時,經(jīng)典問題就是遺留系統(tǒng)需要引用spring管理的bean。幸好spring有機制可以處理這些。

          建一個類實現(xiàn)ApplicationContextAware接口,有一個引用ApplicationContext的靜態(tài)成員,然后,遺留系統(tǒng)需要引用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方法創(chuàng)建的對象可以引用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");
              }
              

          }


          ^_^
          posted on 2007-10-27 16:31 流浪汗 閱讀(15434) 評論(1)  編輯  收藏 所屬分類: Spring

          評論:
          # re: spring 依賴注入到直接new 對象[未登錄] 2011-05-17 17:20 | li
          正好解決了靜態(tài)類需要使用注入對象的問題  回復  更多評論
            
          主站蜘蛛池模板: 虎林市| 黄陵县| 阆中市| 遂宁市| 吴忠市| 开原市| 洛扎县| 通渭县| 深圳市| 都兰县| 福州市| 年辖:市辖区| 秦皇岛市| 军事| 安顺市| 高邮市| 鄱阳县| 汉川市| 栾城县| 民乐县| 临漳县| 瓦房店市| 宣武区| 榆树市| 万山特区| 苍南县| 峡江县| 哈尔滨市| 三门县| 揭西县| 信宜市| 柳河县| 香河县| 呼伦贝尔市| 岫岩| 商都县| 金乡县| 深水埗区| 沭阳县| 黄冈市| 高青县|