spring配置文件默認名稱及位置,ContextLoaderListener監聽器作用


當在新建的maven web項目的web.xml中加入了ContextLoaderListener的監聽后,直接運行程序就會這樣,提示找不到spring的配置文件,且默認位置為/WEB-INF/applicationContext.xml,即默認名稱為applicationContext.xml

spring在web.xml中的配置

由於spring需要啟動容器才能為其他框架提供服務,而web應用程序的入口是由web服務器控制的,因此無法在main()方法中通過創建ClassPathXmlApplicationContext對象來啟動spring容器。spring提供了org.springframework.web.context.ContextLoaderListener(spring-web依賴下)這個監聽器類來解決這個問題。該監聽器實現了ServletContextListener接口,可以在web容器啟動的時候初始化spring容器。當然,前提是需要在web.xml中配置好這個監聽器。如下

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

如果沒有指定contextConfigLoaction參數,ContextLoaderListener默認會去查找/WEB-INF/applicationContext.xml。換句話說,如果我們將spring的配置文件命名為applicationContext.xml並存放在WEB-INF目錄下,即使不指定contextConfigLocation參數,也能加載配置文件。否則就需要配置如下

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext-jdbc.xml</param-value>
</context-param>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM