1. 程式人生 > >在web專案中如何啟動spring容器?

在web專案中如何啟動spring容器?

1.在web.xml配置spring配置檔案的資訊

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

2.在web.xml配置spring監聽

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

以上兩種方式,一般採用第一種方式,第二種方式中ApplicationContextListener是org.springframework.web.context.ContextLoaderListener的子類。ContextLoaderListener實現ServletContextListener,讀取contextConfigLocation中定義的xml檔案,如果不設定contextConfigLocation的初始引數則預設會讀取WEB-INF路徑下的 applicationContext.xml檔案。ContextLoaderListener讀取這些XML檔案併產生 WebApplicationContext物件,然後將這個物件放置在ServletContext的屬性裡,這樣我們只要可以得到Servlet就可以得到WebApplicationContext物件,並利用這個物件訪問spring容器管理的bean。