javascript
Spring初始化:org.springframework.we...ContextLoaderListener的作用
Spring初始化:org.springframework.web.context.ContextLoaderListener的作用
在web.xml種這樣配置
<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>ContextLoaderListener的作用就是啟動Web容器時,自動裝配
ApplicationContext.xml的配置信息。因為它實現了ServletContextListener這個接口,在web.xml配置這個監聽器,啟動容器時,就會默認執行它實現的方法。
applicationContext的默認的路徑是”/WEB-INF/applicationContext.xml。也可以在web.xml中配置該文件的其他位置,配置如下:
<context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value> </context-param>以下是詳解
org.springframework.web.context.ContextLoaderListener類實現了javax.servlet.ServletContextListener接口。ServletContextListener接口能夠監聽ServletContext對象的生命周期,因為每個web應用僅有一個ServletContext對象,故實際上該接口監聽的是整個web應用。
實現該接口的類在web.xml中作為監聽器配置后,當web應用啟動后,會觸發ServletContextEvent事件,調用ContextLoaderListener的contextInitialized(ServletContextEvent sce)方法。
ContextLoaderListener通過一個ContextLoader對象來初始化Spring容器。在contextInitialized方法中調用contextLoader.initWebApplicationContext(event.getServletContext())。
ContextLoader類的initWebApplicationContext方法即可返回一個WebApplicationContext對象context。并通過servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context)將WebApplicationContext對象放置在ServletContext對象中。initWebApplicationContext方法通過調用以下方法實例化并設置WebApplicationContext對象。
因此可以通過WebApplicationContextUtils.getWebApplicationContext(ServletContext sc)獲取WebApplicationContext。內部實現是通過servletContext對象查找該對象,屬性名為WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE。
這篇博文也算是對自己有很多幫助,希望對你有些幫助
總結
以上是生活随笔為你收集整理的Spring初始化:org.springframework.we...ContextLoaderListener的作用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue错误:vue.esm.js?efe
- 下一篇: 如何重启_消费市场按下重启键,企业该如何