1. 程式人生 > >如何在監聽器中獲取spring容器

如何在監聽器中獲取spring容器

第一步: 在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;

  }

   }