Servlet 擷取 ApplicationContext

來源:互聯網
上載者:User

標籤:

 一般使用Spring完成了注入,在Service或SpringMVC 中可以通過註解的形式來擷取 Spring的已經注入的Spring的bean如下所示:

@Resource(name = "userInfoMapper")
private UserInfoMapper userInfoMapper;

 

但是有些情況如在servlet中該如何擷取該對象呢,因為SpringMVC 是基於Servlet的,所有的請求先通過一個預設的Servlet處理——org.springframework.web.servlet.DispatcherServlet(此選項在Web.xml中配置SpringMVC時,必須配置),所以手動建立的Servlet是不能自動擷取注入的Bean的。需要通過ApplicationContext applicationContext 來擷取:

 

this.xmlPacker = ((IXmlPacker) this.applicationContext.getBean("xmlPacker"));

 

applicationContext 的擷取方法是添加一個監聽器,在Context完成時進行初始化,具體的實現方法是:

 

繼承ServletContextListener,重寫contextInitialized,給webCtx賦值。

package com.casic.servlet;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class ApplicationContextInit implements ServletContextListener {
  private static ApplicationContext webCtx = null;

  public void contextDestroyed(ServletContextEvent event) {
  }

  public void contextInitialized(ServletContextEvent event) {
    webCtx = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
  }

  public static ApplicationContext getWebApplicationContext() {
    return webCtx;
  }

  public static void setWebCtx(ApplicationContext webCtx) {
    webCtx = webCtx;
  }
}

在web.xml 中添加監聽器

<listener>

  <listener-class>com.casic.servlet.ApplicationContextInit</listener-class>
</listener>

 

servlet 在 init()函數中使用ApplicationContextInit.getWebApplicationContext() 擷取

public void init() throws ServletException {
  if (this.applicationContext == null) {
    this.applicationContext = ApplicationContextInit.getWebApplicationContext();
    this.xmlPacker = ((IXmlPacker) this.applicationContext.getBean("xmlPacker"));
  }
}

 

Servlet 擷取 ApplicationContext

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.