首页 > 代码库 > Servlet 获取 ApplicationContext
Servlet 获取 ApplicationContext
一般使用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