在搭建 spring mvc 的框架時,會有2個配置文件必不可少: spring-servlet.xml 和applicationContext.xml。第一次接觸spring mvc的工程師可能會對這2個文件的感到疑惑, 下面會對這個兩個文件的配置功能展開闡述:
spring-servlet.xml
如何加載?
顧名思義,是基於servlet的,如果在一個工程A(下面全部命名為A)的結構是類似於web,service,dao的分層,此配置作用於web層會更合理,在工程A的web.xml文件中,如下配置:
由於URL配置是以action結尾的表達式,所以在應用啟動后(這里注意是應用啟動后) ,只要符合此表達式的URL去訪問的應用時,此servlet-class會去響應,同時加載此spring-servlet.xml文件,進行注冊、初始化bean等的系列操作。
如果想要在應用啟動時,servlet即進行響應,可以配置<load-on-startup>1</load-on-startup>
對 load-on-startup 英文原文解釋如下:
Servlet specification:
The load-on-startup element indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the web application. The optional contents of these element must be an integer indicating the order in which the servlet should be loaded. If the value is a negative integer, or the element is not present, the container is free to load the servlet whenever it chooses. If the value is a positive integer or 0, the container must load and initialize the servlet as the application is deployed. The container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the same load-on-start-up value.
翻譯:
-
load-on-startup元素標記容器是否在啟動的時候就加載這個servlet(實例化並調用其init()方法)。
-
它的值必須是一個整數,表示servlet應該被載入的順序
-
當值為0或者大於0時,表示容器在應用啟動時就加載並初始化這個servlet;
-
當值小於0或者沒有指定時,則表示容器在該servlet被選擇時才會去加載。
-
正數的值越小,該servlet的優先級越高,應用啟動時就越先加載。
-
當值相同時,容器就會自己選擇順序來加載。
作用?
可以對視圖文件(如freemarker、jsp等)進行初始化操作,如定義視圖文件的位置,定義全局變量、定義攔截器等等。
applicationContext.xml
如何加載?
顧名思義,是應用上下文、全局的配置。其啟動配置一般在web.xml的Listener節點中, 注意Listener和servlet的區別,加載優先級是Listener大於servlet,同時兩者性質也不同,Listener的操作是對一個事件對象的監聽,而servlet和filter比較類似,是對於URL的一種匹配攔截。
如上圖配置,默認去找classpath下的application-Context.xml,這是一種約定優於配置的概念
同樣也可以配置在context-param的節點中進行配置,如下圖:
加載優先級 : context-param 是大於listener 大於 filter 大於 servlet的
組件掃描最佳配置
在spring-servlet.xml中配置:
<!-- Spring MVC 掃描包路徑配置 -->
<context:component-scan base-package="com.a.b"
use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
在applicationContext.xml中配置:
<!-- 注冊相關后置處理器,掃描包路徑下的注解配置 -->
<context:component-scan base-package="com.a.b">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
參考資料 http://blog.csdn.net/lovesomnus/article/details/51473740