建一個(gè)類實(shí)現(xiàn)ApplicationContextAware接口,有一個(gè)引用ApplicationContext的靜態(tài)成員,然后,遺留系統(tǒng)需要引用spring管理的bean的地方,使用這個(gè)類。
1.比如:我這里建一個(gè)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)建的對(duì)象可以引用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;
}
}
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 此類可以取得Spring的上下文.
* Spring 使new方法創(chuàng)建的對(duì)象可以引用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.其它類中引用

4.如果老是寫(xiě)SpringContext.getContext().getBean("...");麻煩,可以建一個(gè)工廠類來(lái)返回你要的bean
package net.blogjava.chenlb;
public class MyServerFactory {
public static MyBean1 getMyBean1() {
return (MyBean1) SpringContext.getContext().getBean("myBean1");
}
}
public class MyServerFactory {
public static MyBean1 getMyBean1() {
return (MyBean1) SpringContext.getContext().getBean("myBean1");
}
}
^_^