[Spring]web.xml中配置ContextLoaderListener监听器的作用

来源:互联网 发布:农村金融发展数据分析 编辑:程序博客网 时间:2024/06/02 19:58

在spring的核心配置文件中,为什么配置ContextLoaderListener监听器

<listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

打开ContextLoaderListener的源码,发现ContextLoaderListener实现了ServletContextListener接口

/*     */ public class ContextLoaderListener extends ContextLoader/*     */   implements ServletContextListener/*     */ {/*     */   public ContextLoaderListener()/*     */   {/*     */   }/*     */ /*     */   public ContextLoaderListener(WebApplicationContext context)/*     */   {/*  98 */     super(context);/*     */   }/*     */ /*     */   public void contextInitialized(ServletContextEvent event)/*     */   {/* 106 */     initWebApplicationContext(event.getServletContext());/*     */   }/*     */ /*     */   public void contextDestroyed(ServletContextEvent event)/*     */   {/* 115 */     closeWebApplicationContext(event.getServletContext());/* 116 */     ContextCleanupListener.cleanupAttributes(event.getServletContext());/*     */   }/*     */ }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

实现了ServletContextListener接口的作用就是当项目一经启动,就会激活实现了此接口的类方法,可以进行相关的初始化操作。 
ServletContextListener接口实现了 
public void contextInitialized(ServletContextEvent event)与 
public void contextDestroyed(ServletContextEvent event) 
两个方法, 
意味着项目一经启动,会进入contextInitialized方法中,进行Spring的相关配置。并且contextInitialized方法有ServletContext参数,可以在web.xml中配置参数,用来ServletContext读取相关Spring配置文件, 一般 Dao, Service 的 Spring 配置都会在 listener 里加载。 
项目退出时激活contextDestroyed方法。

结尾:

1. 如果只有 Spring mvc 的一个 Servlet,listener 可以不用。2. 但是如果用了Shiro 等,Shiro 用到的 Spring 的配置必须在 listener 里加载。3. 一般 Dao, Service 的 Spring 配置都会在 listener 里加载,因为可能会在多个 Servlet 里用到,因为父子 Context 的可见性问题,防止重复加载所以在 listener 里加载。所以,有时可用可不用,有时必用,具体看情况。 
阅读全文
1 0
原创粉丝点击