Spring中配置ContextLoaderListener方式
更新時間:2025年04月11日 10:50:32 作者:長不大的大灰狼
這篇文章主要介紹了Spring中配置ContextLoaderListener方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
Spring中配置ContextLoaderListener
web.xml:
<!-- contextConfigLocation參數(shù)用來指定Spring的配置文件 needed for ContextLoaderListener --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-persist-*.xml</param-value> </context-param> <!-- 配置spring核心監(jiān)聽器 Bootstraps the root web application context before servlet initialization --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
ContextLoaderListener的作用是什么?
ContextLoaderListener的作用就是啟動Web容器時,讀取在contextConfigLocation中定義的xml文件,自動裝配ApplicationContext的配置信息,并產(chǎn)生WebApplicationContext對象,然后將這個對象放置在ServletContext的屬性里,這樣我們只要得到Servlet就可以得到WebApplicationContext對象,并利用這個對象訪問spring容器管理的bean。
簡單來說,就是上面這段配置為項目提供了spring支持,初始化了Ioc容器。
web.xml 中 ContextLoaderListener 是否可以不配置?
- 如果只有 Spring mvc 的一個 Servlet,listener 可以不用。
- 但是如果用了Shiro 等,Shiro 用到的 Spring 的配置必須在 listener 里加載。
- 一般 Dao, Service 的 Spring 配置都會在 listener 里加載,因為可能會在多個 Servlet 里用到,而且父子 Context 間存在可見性問題,所以,為了防止重復加載需要在 listener 中進行加載。
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
IDEA下Servlet可能出現(xiàn)404的一些情況
相信有很多小伙伴遇到報錯都不知道怎么處理,今天特地整理了這篇文章,文中對IDEA下Servlet可能出現(xiàn)404的一些情況作了詳細的介紹,需要的朋友可以參考下2021-06-06Spring Boot thymeleaf模板引擎的使用詳解
這篇文章主要介紹了Spring Boot thymeleaf模板引擎的使用詳解,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03