天天看點

Spring內建web環境

1. ApplicationContext應用上下文擷取方式

2. Spring提供擷取應用上下文的工具

3. 案例測試

應用上下文對象是通過<code>new ClasspathXmlApplicationContext(spring配置檔案)</code> 方式擷取的,但是每次從容器中獲得Bean時都要編寫<code>new ClasspathXmlApplicationContext(spring配置檔案)</code> ,這樣的弊端是配置檔案加載多次,應用上下文對象建立多次。

在Web項目中,可以使用<code>ServletContextListener</code>監聽Web應用的啟動,我們可以在Web應用啟動時,就加載Spring的配置檔案,建立應用上下文對象<code>ApplicationContext</code>,在将其存儲到最大的域<code>servletContext域中,這樣就可以在任意位置從域中獲得應用上下文</code>ApplicationContext`對象了。

上面的分析不用手動實作,Spring提供了一個監聽器<code>ContextLoaderListener</code>就是對上述功能的封裝,該監聽器内部加載Spring配置檔案,建立應用上下文對象,并存儲到<code>ServletContext</code>域中,提供了一個用戶端工具<code>WebApplicationContextUtils</code>供使用者獲得應用上下文對象。

是以我們需要做的隻有兩件事:

1、在<code>web.xml</code>中配置<code>ContextLoaderListener</code>監聽器(導入spring-web坐标)

2、使用<code>WebApplicationContextUtils</code>獲得應用上下文對象<code>ApplicationContext</code>

先準備好 UserDao、UserDaoImpl、UserService、UserServiceImpl

建立 Servlet 類 充當 web 層

UserDaoImpl

Spring內建web環境

UserServiceImpl

Spring內建web環境

導入Spring內建web的坐标 和 Servlet 依賴

配置<code>ContextLoaderListener</code>監聽器,在 <code>web.xml</code> 配置下

Spring內建web環境

建立 Servlet 類 充當 web 層,通過工具獲得應用上下文對象

運作:http://localhost:8080/userServlet

Spring內建web環境