Spring在web.xml中的配置詳細介紹
前言
在實際項目中spring的配置文件applicationcontext.xml是通過spring提供的加載機制自動加載到容器中。在web項目中,配置文件加載到web容器中進行解析。目前,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的引用。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
|
新聞熱點
疑難解答