1. 程式人生 > >13.Spring-Web專案下使用Spring容器

13.Spring-Web專案下使用Spring容器

QQ群:Java資料共享群 59174518

假設按照我們學習的方法來建立ApplicationContext容器的話

   @Test
    public void fun1() {
        // 1.首先要把容器創建出來,
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        // 2.向容器裡面獲取到user物件
        User user = (User) applicationContext.getBean
("user"); // 3.列印獲取到的user物件. System.out.println(user); }

每次呼叫方法的時候,都會建立一個容器,如果是呼叫多個物件? 這樣會照成整個專案的容器過多,效能多差.

如何確保專案中只有一個ApplicationContext容器?

  • Spring已經提供好了一個監聽器來實現這個功能
  • 這個監聽器可以讓ApplicationContext容器隨著專案的啟動而啟動,專案的銷燬而銷燬
  • 首先導包:spring-web-4.2.4.RELEASE.jar
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Spring-01</display-name> <welcome-file-list
>
<welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- 指定監聽器 --> <!-- 這個就能讓Spring容器可以隨專案的啟動而啟動 ,專案的銷燬而銷燬 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 通過 context-param 指定載入Spring配置檔案--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:ApplicationContext.xml</param-value> </context-param> </web-app>

配置要如何後要如何獲取到這個容器?

  • 以為容器在建立好之後是在監聽器中建立的,在監聽器中是可以獲取事件源的.所以可以獲取到Sping容器物件.
  • 就是Application域;所以只要在Application域裡面獲取就好.Application域裡面存放是的鍵值對.所以我要知道key,value才行
  • 所以Spirng把這個鍵值對封裝在一個工具方法裡面,這個工具方法是"WebApplicationContextUtils.getWebApplicationContext(sc)"