Web項目如何初始化SpringIOC容器 :思路:當服務啟動時(tomcat),通過監聽器將SpringIOC容器初始化一次(該監聽器 spring-web.jar已經提供),web項目啟動時 ,會自動加載web.xml,因此需要在web.xml中加載 監聽器(ioc容器初始化)。所謂的ioc容器其實相當於applicationContext.xml配置文件,把所有被ioc管理的對象放入其中,放入bean標簽里,當做對象管理!!!
<!-- 指定 Ioc容器(就是applicationContext.xml)的位置--> <context-param> <!-- 監聽器的父類ContextLoader中有一個屬性contextConfigLocation,該屬性值 保存着 容器配置文件applicationContext.xml的位置 --> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <!-- 配置spring-web.jar提供的監聽器,此監聽器 可以在服務器啟動時 初始化Ioc容器。 初始化Ioc容器(applicationContext.xml) , 1.告訴監聽器 此容器的位置:context-param 2.默認約定的位置 :WEB-INF/applicationContext.xml --> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
實例:
<?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_3_0.xsd" version="3.0"> <display-name>crm-test</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讀取的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring_dao.xml classpath:spring_service.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置編碼過濾 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置前端控制器 --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-web-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- jfree配置 --> <servlet> <servlet-name>DisplayChart</servlet-name> <servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class> </servlet> <servlet-mapping> <servlet-name>DisplayChart</servlet-name> <url-pattern>/chart</url-pattern> </servlet-mapping> </web-app>