【随笔】Spring中的监听器ContextLoaderListener

ContextLoaderListener监听器的作用就是启动Web容器时,自动装配ApplicationContext的配置信息;源码如下

package org.springframework.web.context;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ContextLoaderListener extends ContextLoader
  implements ServletContextListener
{
  public ContextLoaderListener()
  {
  }

  public ContextLoaderListener(WebApplicationContext context)
  {
    super(context);
  }

  public void contextInitialized(ServletContextEvent event)
  {
    initWebApplicationContext(event.getServletContext());
  }

  public void contextDestroyed(ServletContextEvent event)
  {
    closeWebApplicationContext(event.getServletContext());
    ContextCleanupListener.cleanupAttributes(event.getServletContext());
  }
}
可以看出其实现了ServletContextListener接口中的contextInitialized和contextDestroyed两个方法。 ServletContextListener 是 ServletContext 的监听者,如果 ServletContext 发生变化,如服务器启动时 ServletContext 会被创建,服务器关闭时 ServletContext 将要被销毁。而整个加载过程由ContextLoader来完成,spring中的bean也由其创建。


Spring MVC,你可以使用监听器Listener)来监听请求和响应的事件。Spring MVC提供了一些内置的监听器,你可以使用它们来拦截和处理请求。以下是一些常用的监听器: 1. ContextLoaderListener:这是一个ServletContext监听器,用于加载Spring应用程序上下文。它可以在应用程序启动时初始化Spring容器,并在应用程序关闭时进行资源清理。 2. RequestContextListener:这是一个ServletRequest监听器,用于绑定当前请求的Locale和Theme到Spring的上下文。它允许你在控制器和视图访问当前请求的Locale和Theme。 3. HttpSessionListener:这是一个HttpSession监听器,用于跟踪会话的创建和销毁。你可以通过实现该监听器来执行自定义的会话管理逻辑。 4. ServletRequestListener:这是一个ServletRequest监听器,用于跟踪请求的创建和销毁。你可以通过实现该监听器来执行自定义的请求处理逻辑。 要使用这些监听器,你需要在web.xml文件进行配置。例如,以下是在web.xml配置ContextLoaderListener的示例: ```xml <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> ``` 请注意,以上示例的类名是一个示例,具体的类名可能会因你使用的Spring版本而有所不同。你需要根据你的Spring版本选择正确的类名。 希望这能帮到你!如果你还有其他问题,请继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值