在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 里加载。
所以,有时可用可不用,有时必用,具体看情况。
本文解析了Spring中ContextLoaderListener的作用及其实现原理。通过监听项目的启动与关闭过程,该组件负责初始化和销毁Spring的Web应用上下文,确保相关配置正确加载。
1101

被折叠的 条评论
为什么被折叠?



