當為遺留系統加入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");
}
}
^_^
posted on 2007-10-27 16:31
流浪汗 閱讀(15425)
評論(1) 編輯 收藏 所屬分類:
Spring