Spring加載applicationContext

Spring加載上下文的方式有兩種:

  1. 監聽加載 ContextLoaderListener
  2. servlet加載 DispatcherServlet
這兩種加載的方式產生的效果是不一樣的,ContextLoaderListener是作用於全局,DispatcherServlet加載是作用於私有的。
WebApplicationContextUtils.getWebApplicationContext(servletContext)
通過這個方法,可以獲取全局的上下文,但是DispatcherServlet加載信息不在這個全局裏面,對,你可以嘗試一下,它確實
不在全局上下文中。那我怎麼獲取它?

如果DispatcherServlet的屬性
如果 publishContext屬性的值設置爲true的話(缺省爲true) 會將applicationContext存放在request.getSession().getServletContext(),DispatcherServlet.SERVLET_CONTEXT_PREFIX + (servletName)的attribute中。
<!-- 配置Spring核心控制器 -->
	<servlet>
	    <servlet-name>dispatcher</servlet-name>
	    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	    <init-param>
	        <param-name>contextConfigLocation</param-name>
	        <param-value>/WEB-INF/spring-mvc.xml</param-value>
	    </init-param>
	    <load-on-startup>1</load-on-startup>
	</servlet>
	 
	<servlet-mapping>
	    <servlet-name>dispatcher</servlet-name>
	    <url-pattern>/</url-pattern>
	</servlet-mapping>
WebApplicationContextUtils.getWebApplicationContext(servletContext,attribute) 就可以取到私有的上下文信息了。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章