標籤:
一般使用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