如何在监听器中获取spring容器

来源:互联网 发布:软件开发设计方案 编辑:程序博客网 时间:2024/06/08 04:01

第一步: 在web.xml定义 request的上下文

代码如下:

<!-- request上下文监听 -->
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

第二步 通过
request上下文得到servletContext,从而得到applicationContext(注:可以将该代代码封装到工具类中)

代码如下:

HttpServletRequestrequest =((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

         applicationContext= WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());

封装工具类的代码如下:

publicclassApplicationContextUtils {

   privatestatic ApplicationContext applicationContext;

   publicstatic ApplicationContextgetApplicationContext(){

      if(applicationContext ==null){

         HttpServletRequestrequest = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

         applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());

       }

      returnapplicationContext;

   }

   }

0 0
原创粉丝点击