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

在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了。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值