天天看點

Spring中DispatcherServlet與ContextLoaderListener的差別

昨天在寫springmvc的時候,在web.xml中配置了DispatcherServlet,如下:

<servlet>
		<servlet-name>DispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:applicationContext.xml</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>DispatcherServlet</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>      

 想到以前寫ssh的時候,web.xml中配置的都是listener,如下:

<listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>/WEB-INF/classes/applicationContext-*.xml</param-value>
  </context-param>
           

 他們都是去加載spring的配置檔案,那麼他們有什麼不同呢?後來在網上查了下資料,發現他們的作用域是不同的,在dispatcherServlet中加載的配置檔案的作用域是在web請求的時候才觸發的,一般跟controller相關的bean配置會放在這裡面,例如視圖解析器的bean,而ContextLoaderListener加載的配置檔案的作用域是在整個環境中,類似于application級别的,一般在這個配置檔案中定義的是公共的内容,例如db、service等等。寫的很淺,歡迎拍磚....