备忘-在spring web应用中获得ApplicationContext的引用

来源:互联网 发布:手机上传淘宝图片模糊 编辑:程序博客网 时间:2024/05/18 01:18
在spring和各种MVC整合的框架下,在我们自己写的代码中要使用ApplicationContext是不方便的。

spring有一个类
org.springframework.web.context.support.WebApplicationContextUtils

它有一个static的方法 getWebApplicationContext(ServletContext sc) 可以使我们得到一个ApplicationContext的引用,
但这个方法有一个参数ServletContext,它是Servlet容器提供的上下文,在非Servlet环境下是得不到的。

我们可以定义一个servlet,该servlet配置为被容器第一个加载,它可以得到ServletContext,从而得到ApplicationContext的引用,
我们再把这个引用保存在一个所用应用都能访问到的地方。

  1. package xxx.utils;
  2. import org.springframework.context.ApplicationContext;
  3. public class SpringBeanProxy {
  4.     private static ApplicationContext applicationContext;
  5.     
  6.     public synchronized static void setApplicationContext(ApplicationContext arg0) {
  7.         applicationContext = arg0;
  8.     }
  9.     
  10.     public static Object getBean(String beanName){
  11.         return applicationContext.getBean(beanName);
  12.     }
  13. }

  1. package xxx.servlets;
  2. import javax.servlet.ServletConfig;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.http.HttpServlet;
  5. import org.springframework.web.context.support.WebApplicationContextUtils;
  6. import xxx.utils.SpringBeanProxy;
  7. public class SpringBeanInitServlet  extends HttpServlet {
  8.     public void init(ServletConfig arg0) throws ServletException {
  9.         SpringBeanProxy.setApplicationContext(WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext()));
  10.     }
  11. }

在web.xml中
  1.     <listener>
  2.         <listener-class>
  3.             org.springframework.web.context.ContextLoaderListener
  4.         </listener-class>
  5.     </listener>
  6.     <servlet>
  7.         <servlet-name>SpringBeanInitServlet</servlet-name>
  8.         <servlet-class>
  9.             xxx.SpringBeanInitServlet
  10.         </servlet-class>
  11.         <load-on-startup>1</load-on-startup>
  12.     </servlet>
由于listener先于servlet加载,所以可以确保SpringBeanInitServlet加载时spring已经初始化好了,
如果你使用的是servlet加载spring就要注意调整这两个servlet的启动顺序了。


这时可以在程序的任何地方,使用 SpringBeanProxy.getBean("beanName")得到一个bean了。