最近想要搞一个责任链模式玩玩,并且希望每次只添加新类,但不修改原有的代码,所以想通过反射来获取责任链中的每一个环节的对象,但是因为是通过@Resource注解自动装配的,所以newInstance导致里边自动装配的属性全都为null,最后找到方法要通过ApplicationContext来创建对象,但是这时有出现了问题,因为我对spring了解不是很深入,所以究竟该怎么获取ApplicationContext呢?于是乎发现了下面这篇文章,很有帮助。
------------------------------转载分割线---------------------------------------------------------------------------------------------------------
Web项目中发现有人如此获得Spring的上下环境:
public class SpringUtil {
public static ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
public static Object getBean(String serviceName){
return context.getBean(serviceName);
}
}
在web项目中这种方式非常不可取!!!
分析:
首先,主要意图就是获得Spring上下文;
其次,有了Spring上下文,希望通过getBean()方法获得Spring管理的Bean的对象;
最后,为了方便调用,把上下文定义为static变量或者getBean方法定义为static方法;
但是,在web项目中,系统一旦启动,web服务器会初始化Spring的上下文的,我们可以很优雅的获得Spring的ApplicationContext对象。
如果使用
new ClassPathXmlApplicationContext("applicationContext.xml");
相当于重新初始化一遍!!!!
也就是说,重复做启动时候的初始化工作,第一次执行该类的时候会非常耗时!!!!!
正确的做法是:
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext; // Spring应用上下文环境
/*
* 实现了ApplicationContextAware 接口,必须实现该方法;
*通过传递applicationContext参数初始化成员变量applicationContext
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T) applicationContext.getBean(name);
}
}
注意:这个地方使用了Spring的注解@Component,如果不是使用annotation的方式,而是使用xml的方式管理Bean,记得写入配置文件
<bean id="springContextUtil" class="com.ecdatainfo.util.SpringContextUtil" singleton="true" />
其实
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
这种方式获取Sping上下文环境,最主要是在测试环境中使用,比如写一个测试类,系统不启动的情况下手动初始化Spring上下文再获取对象!