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

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

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

打开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());
/*     */   }
/*     */ }

实现了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 里加载。

所以,有时可用可不用,有时必用,具体看情况。 
  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值