浅谈配置文件:spring-servlet.xml(spring-mvc.xml) 与 applicationContext.xml

在搭建 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

posted @ 2017-09-19 17:17  ppjj  阅读(10035)  评论(0编辑  收藏  举报