一、作用
ContextLoaderListener監聽器的作用就是啟動web容器時,自動裝配ApplicationContext的配置信息。它實現了ServletContextListener接口,在web.xml文件中配置這個監聽器,啟動容器時,就會默認執行它實現的方法。
二、ContextLoader
ContextLoaderListener關聯了ContextLoader,整個加載配置過程也是由ContextLoader來完成的。
1. ContextLoader可以由ContextLoaderListener和ContextLoaderServlet生成。ContextLoaderServlet不僅繼承了ContextLoader,而且也實現了HttpServlet方法。
2. ContextLoader創建了WebApplicationContext,它繼承了ApplicationContext —> BeanFactory,說明Spring的所有bean也是在ContextLoader中創建的。
三、如何配置applicationContext.xml文件
1. 采用默認配置路徑。將applicationContext.xml放置在WEB-INF下,不能自定義文件名。然后只需在web.xml中配置。
<!-- Spring Listener --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
2. 指定配置文件。需要在web.xml中配置參數指定文件路徑。然后仍需配置上面代碼中的監聽器。
<!-- 參 數:Spring配置路徑 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param>
四、擴展
如果有多個xml文件,可以寫在一起並用","號分隔。也可以采用通配符的形式,applicationContext-*.xml,符合條件的文件都會被一同加載。