Spring配置中ContextLoaderListener的理解
每一个整合spring框架的项目中,都要在web.xml中加入这样一段配置
ContextLoaderListener继承自ContextLoader,实现的是ServletContextListener接口。
- 继承ContextLoader有什么作用?
ContextLoaderListener可以指定在Web应用程序启动时载入Ioc容器,正是通过ContextLoader来完成Ioc容器的初始化工作。
- 实现ServletContextListener又有什么作用?
ServletContextListener接口里的函数会结合Web容器的生命周期被调用。因为ServletContextListener是ServletContext的监听者,如果ServletContext发生变化,会触发相应的事件,而监听器一直对事件监听,如果接收到了变化,就会做出预先设计好的相应动作。由于ServletContext变化而触发的监听器的响应具体包括:在服务器启动时,ServletContext被创建的时候,服务器关闭时,ServletContext将被销毁的时候等。
- 那么ContextLoaderListener的作用是什么?
ContextLoaderListener的作用就是启动Web容器时,读取在contextConfigLocation中定义的xml文件,自动装配ApplicationContext的配置信息,并产生applicationcontext对象,然后将这个对象放置在ServletContext的域里(通过setAttribute方法),这样我们通过ServletContext就可以得到共享的applicationcontext对象(避免了new ClassPathApplicationContext(“applicationContext.xml”)的重复加载),并利用这个对象访问spring容器管理的bean(applicationcontext.getBean(类名.class))。
简单来说,就是上面这段配置为项目提供了spring支持,初始化了Ioc容器。
- 那又是怎么为我们的项目提供spring支持的呢?
监听器一直对事件监听,如果接收到了变化,就会做出预先设计好的相应动作,而监听器的响应动作就是在服务器启动时contextInitialized会被调用,关闭的时候contextDestroyed被调用。