在普通web项目的servlet和filter中获取spring上下文

来源:互联网 发布:2017药品中标数据目录 编辑:程序博客网 时间:2024/05/01 03:00

文章来源:http://blog.csdn.net/zhiweiv/archive/2008/10/21/3118857.aspx

 

 

之前一直是在web项目中使用struts2然后通过plugin集成spring,action生成的细节全部由plugin实现了,对于我们是透明的。过几天学校留个作业只能用普通的jsp+servlet做,之前一直是透明的使用spring,对spring的初始化及bean的获取一直没什么概念。这回正好用的上,就研究了一下ContextLoaderListener ContextLoader和StrutsSpringObjectFactory的源码。经过一番阅读对spring的初始化和获取bean有了一些印象。


    在spring中的org.springframework.beans.factory.BeanFactory接口getBean(String id)用来获取spring管理的bean。而我们一般使用实现了该接口的ApplicationContext接口。所以只要我们在servlet中取得了ApplicationContext接口的实现类,就可以获取spring管理的bean了。

    首先是在web.xml中配置listener
  1. <listener>
  2.     <listener-class>
  3.         org.springframework.web.context.ContextLoaderListener
  4.     </listener-class>
  5. </listener>
     这个类的核心代码如下
  1. //实例化一个ContextLoader,然后调用它的initWebApplicationContext方法
  2. public void contextInitialized(ServletContextEvent event) {
  3.      this.contextLoader = createContextLoader();
  4.      this.contextLoader.initWebApplicationContext(event.getServletContext());
  5. }
  6. protected ContextLoader createContextLoader() {
  7.       return new ContextLoader();
  8. }
    ContextLoader这个类内的代码就不写了,看不太明白。然后一个必须的类是WebApplicationContextUtils,该类有一个方法getWebApplicationContext(ServletContext servletContext),这个方法的官方解释是: Find the root WebApplicationContext for this web application, which is typically loaded via ContextLoaderListener or ContextLoaderServlet它的大概意思就是这个方法通过ContextLoaderListener获取WebApplicationContext。所以在servlet中就可以通过如下方法实现获取spring上下文
  1. import javax.servlet.http.HttpServlet;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.web.context.support.WebApplicationContextUtils;
  4. public class NewServlet extends HttpServlet {
  5.    
  6.     public ApplicationContext getApplicationContext(){
  7.         return WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
  8.     }
  9. }

    使用方法
  1. public void test(){
  2.         TestBean testBean=(TestBean)this.getApplicationContext().getBean("testBean");
  3.     }

   在filter里面server会给它注入一个FilterConfig对象,在filter里可以使用FilterConfig的filterConfig.getServletContext()方法获取servlet上下文,所以在filter里获取spring的上下文方法如下

  1. public ApplicationContext getApplicationContext() {
  2.     return WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
  3. }