在action中我们均可以利用框架本身的一些配置文件(struts.xml和applicationContext.xml)来获取spring容器,从而获取到容器中的bean。
但是在非action的类中,该类不是一个aciton,所以不通过struts.xml来配置,自然我们也无法直接用配置的方法去引用一个bean。笔者就遇到了这个问题。场景是在websocket类(类名为chatServer)中需要调用Service类(类名为UserHoldService),该Service类调用了dao类进行数据操作。
在传统的action类里,我们可以像下面这样通过ssh框架自动获取Service类。
private UserHoldService userHoldService;
public void setUserHoldService(UserHoldService userHoldService){
this.userHoldService=userHoldService;
}
然后在applicationContext.xml中去配置
<bean id="xxxAction" class="com.wonyen.action.XxxAction" scope="prototype">
<property name="userHoldService" ref="userHoldService" />
</bean>
然后再去struts.xml配置相应的路径。
但是由于我这边的类是一个普通的java类,所以必须自己去获取spring容器,也就是applicationContext。上网查了很多种方法,首先用了下面这个方法。
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
经验证是可行的,但是有个问题,就是执行这句代码的时候很耗时。本人猜测这句代码会重新new一个容器对象,相当于重新载入了一次applicationContext.xml里面配置的类,而不是去拿在项目启动之初生成的那个spring容器对象。
后面搜索到了这个方法,可以拿到现成的spring容器对象。
1.首先建立一个工具类
package com.wonyen.util; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class MySpringContext implements ApplicationContextAware { private static ApplicationContext context;//声明一个静态变量用于保存spring容器上下文 @Override public void setApplicationContext(ApplicationContext context) throws BeansException { this.context=context; } public static ApplicationContext getContext(){ return context; } }
可见该工具类实现了ApplicationContextAware接口,实现该接口的类会接收到spring容器传过来的ApplicationContext对象,从而可以实现操纵spring容器中的所有bean的效果。但是这里我们并不在这个工具类里面去获取bean,我们暂且把获取来的ApplicationContext对象存放起来,放在哪里呢,就是放在该类的一个静态变量中context中,然后我们再给它一个静态的get方法,供其他的类去调用。
2.有了这个工具类还没用,spring容器不会无缘无故去执行setApplicationContext方法把ApplicationContext 对象传入给它,所以必须在ApplicationContext.xml文件里面去配置,如下所示。
<!-- util --> <bean class="com.wonyen.util.MySpringContext"></bean>
这样,当项目启动时,就会加载这个工具类,并把ApplicationContext 传入。
3.在其他类调用,只需要这样一行代码就可以了。
ApplicationContext context =MySpringContext.getContext();
经验证,采用这种方式获取的ApplicationContext的速度明显比前面那种快很多。
原文:http://www.cnblogs.com/roy-blog/p/6362411.html