Chinaunix首页 | 论坛 | 博客

acc

  • 博客访问: 790991
  • 博文数量: 170
  • 博客积分: 7011
  • 博客等级: 少将
  • 技术积分: 1660
  • 用 户 组: 普通用户
  • 注册时间: 2006-07-31 12:02
文章分类

全部博文(170)

文章存档

2014年(7)

2010年(2)

2009年(62)

2008年(25)

2007年(67)

2006年(7)

我的朋友

分类: Java

2010-07-06 21:15:19

 

在spring和各种MVC整合的框架下,在我们自己写的代码中要使用ApplicationContext是不方便的。

spring有一个类

org.springframework.web.context.support.WebApplicationContextUtils它有一个static的方法 getWebApplicationContext(ServletContext sc) 可以使我们得到一个ApplicationContext的引用,但这个方法有一个参数ServletContext,它是Servlet容器提供的上下文,在非Servlet环境下是得不到的。我们可以定义一个servlet,该servlet配置为被容器第一个加载,它可以得到ServletContext,从而得到ApplicationContext的引用,我们再把这个引用保存在一个所用应用都能访问到的地方。package xxx.utils;import org.springframework.context.ApplicationContext;public class SpringBeanProxy {    private static ApplicationContext applicationContext;        public synchronized static void setApplicationContext(ApplicationContext arg0) {        applicationContext = arg0;    }        public static Object getBean(String beanName){        return applicationContext.getBean(beanName);    }}package xxx.servlets;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import org.springframework.web.context.support.WebApplicationContextUtils;import xxx.utils.SpringBeanProxy;public class SpringBeanInitServlet  extends HttpServlet {    public void init(ServletConfig arg0) throws ServletException {        SpringBeanProxy.setApplicationContext(WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext()));    }}在web.xml中                        org.springframework.web.context.ContextLoaderListener                        SpringBeanInitServlet                    xxx.SpringBeanInitServlet                1    由于listener先于servlet加载,所以可以确保SpringBeanInitServlet加载时spring已经初始化好了,如果你使用的是servlet加载spring就要注意调整这两个servlet的启动顺序了。这时可以在程序的任何地方,使用 SpringBeanProxy.getBean("beanName")得到一个bean了。

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/dqatsh/archive/2008/12/07/3469278.aspx

阅读(1215) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~