更新時間:2020-06-20 12:28:32 來源:動力節點 瀏覽1992次
今天咱們要學習的是SpringMVC框架中Spring與Web環境集成的內容,主要涉及的知識點有ApplicationContext應用上下文獲取方式,Spring提供獲取應用上下文的工具,導入Spring集成web的坐標,配置ContextLoaderListener監聽器以及通過工具獲得應用上下文對象。下面我們來看看具體的學習內容吧~
1、ApplicationContext應用上下文獲取方式
應用上下文對象是通過new ClasspathXmlApplicationContext(spring配置文件)方式獲取的,但是每次從容器中獲得Bean時都要編寫new ClasspathXmlApplicationContext(spring配置文件),這樣的弊端是配置文件加載多次,應用上下文對象創建多次。
在Web項目中,可以使用ServletContextListener監聽Web應用的啟動,我們可以在Web應用啟動時,就加載Spring的配置文件,創建應用上下文對象ApplicationContext,在將其存儲到最大的域servletContext域中,這樣就可以在任意位置從域中獲得應用上下文ApplicationContext對象了。
2、Spring提供獲取應用上下文的工具
上面的分析不用手動實現,Spring提供了一個監聽器ContextLoaderListener就是對上述功能的封裝,該監聽器內部加載Spring配置文件,創建應用上下文對象,并存儲到ServletContext域中,提供了一個客戶端工具WebApplicationContextUtils供使用者獲得應用上下文對象。
所以我們需要做的只有兩件事:
一是在web.xml中配置ContextLoaderListener監聽器(導入spring-web坐標);二是使用WebApplicationContextUtils獲得應用上下文對象ApplicationContext。
3、導入Spring集成web的坐標
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
4、配置ContextLoaderListener監聽器
<!--全局參數-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--Spring的監聽器-->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
5、通過工具獲得應用上下文對象
ApplicationContext applicationContext=
WebApplicationContextUtils.getWebApplicationContext(servletContext);
Object obj=applicationContext.getBean("id");
最后,總結一下Spring與Web環境集成的知識要點:Spring集成web環境步驟是先配置ContextLoaderListener監聽器,然后使用WebApplicationContextUtils獲得應用上下文。
以上就是動力節點java培訓機構的小編針對“Java并發教程:Spring與Web環境集成總結”的內容進行的回答,希望對大家有所幫助,如有疑問,請在線咨詢,有專業老師隨時為你服務。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習