在實際項目中spring的配置文件applicationcontext.xml是通過spring提供的加載機制自動加載到容器中,但是有許多朋友們不知道Spring在web.xml中的配置到底是怎樣的,現在我們去看看Spring在web.xml中的配置介紹。
目前,spring提供了兩種加載器,以供web容器的加載:一種是ContextLoaderListener,另一種是ContextLoaderServlet。這兩種在功能上完全相同,只是前一種是基于Servlet2.3版本中新引入的Listener接口實現,而后一種是基于Servlet接口實現,以下是這兩種加載器在web.xml中的配置應用:
ContextLoaderListener
<listener> <listener-class>org.springframework.context.ContextLoaderListener</listener-class> </listener>
ContextLoaderServlet
<servlet> <servlet-name>context</servlet-name> <servlet-class>org.springframework.context.ContextLoaderServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet>
???? 通過上面的配置,web容器會自動加載applicationcontext.xml初始化。
???? 如果需要指定配置文件的位置,可通過context-param加以指定:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/myApplicationContext.xml</param-value> </context-param>
???? 之后,可以通過WebApplicationContextUtils.getWebApplicationContext方法在web應用中獲取applicationcontext的引用。
看完上述Spring在web.xml中的配置介紹后,按照以上步驟應該不會出問題,有問題可以留言給我們錯新技術頻道哦。
新聞熱點
疑難解答