1. 程式人生 > >spring專案中,web.xml中的 ContextLoaderListener監聽器的原理

spring專案中,web.xml中的 ContextLoaderListener監聽器的原理

</pre><pre class="java" name="code">建立監聽器和ServletContext的code:
</pre><pre class="java" name="code"><context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath*:applicationContext-*.xml</param-value>
 </context-param>

<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

ContextLoaderListener的作用(一句話):初始化BeanFactory,並將BeanFactory設定到application中。

說明:

建立了ContextLoaderListener這個監聽器,它繼承了ContextLoader類、實現了ServletContextListener介面,監聽器對Application的建立進行了監聽

ServletContext建立了,這個事件就會被監聽器的contextInitlized(ServletContext event)方法監聽到;

application設定到contextLoader屬性上;

    執行原始碼的

this.contextLoader.initWebApplicationContext(event.getServletContext());

取出web.xmlcontextConfigLocation引數的值,也就是spring的配置資訊;

根據這些配置資訊生成Bean工廠;

最後把這個bean工廠設定到application中去;

可以在後端處理器(Action)中通過application取出beanFactory,進而從beanFactory取出業務物件,進行業務操作。

 --------------------------------------------------------------------------------

在spring、springMVC,專案中這種配置,具有通用性。