第一步: 在web.xml定义 request的上下文
代码如下:
<!-- request上下文监听 -->
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
第二步 通过request上下文得到servletContext,从而得到applicationContext(注:可以将该代代码封装到工具类中)
代码如下:
HttpServletRequest request =((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
applicationContext= WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
封装工具类的代码如下:
public classApplicationContextUtils {
private static ApplicationContext applicationContext;
public static ApplicationContextgetApplicationContext(){
if(applicationContext == null){
HttpServletRequestrequest = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
}
return applicationContext;
}
}