由於監聽器是在web.xml上配置的,因此在代碼中注入Bean,並不受spring框架的支持,因此須要加入如下代碼。java
VistedAnalyticsService vistedAnalyticsService = (VistedAnalyticsService) this .getObjectFromApplication(sessionEvent.getSession().getServletContext(), "vistedAnalyticsService");
/** * 經過WebApplicationContextUtils 獲得Spring容器的實例。根據bean的名稱返回bean的實例。 * * @param servletContext * :ServletContext上下文。 * @param beanName * :要取得的Spring容器中Bean的名稱。 * @return 返回Bean的實例。 */ private Object getObjectFromApplication(ServletContext servletContext, String beanName) { // 經過WebApplicationContextUtils 獲得Spring容器的實例。 ApplicationContext application = WebApplicationContextUtils.getWebApplicationContext(servletContext); // 返回Bean的實例。 return application.getBean(beanName); }