Spring 框架学习(二):Spring 应用配置文件解析

[TOC]

Spring 框架学习(二):Spring 应用配置文件解析

初学 Spring 的时候,只是照猫画虎,对于每一项配置的由来并不十分了解。这里,我们深入了解一下,这些配置都起到了什么作用?

web.xml

应用启动的时候,Tomcat 容器会读取 web.xml 配置文件,一个正常的 web.xml 示例如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.css</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.gif</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.jpg</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>http_filter</filter-name>
        <filter-class>com.xxx.HttpFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>http_filter</filter-name>
        <url-pattern>/api/search.json</url-pattern>
    </filter-mapping>
</web-app>

context-param 节点存储的键值对会被存入 ServletContext 中,后续可以通过其 getInitParameter 得到其值,

ServletContext sc;
String configLocationParam = sc.getInitParameter("contextConfigLocation");

listener 节点存放的 ContextLoaderListene 类实现了接口 ServletContextListener,会监听 Web 容器的初始化和关闭,做相应的初始化和销毁工作:

public interface ServletContextListener extends EventListener {
    void contextInitialized(ServletContextEvent var1);

    void contextDestroyed(ServletContextEvent var1);
}

Spring 容器就是在 ContextLoaderListener 的 contextInitialized 方法中被初始化:

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
    public void contextInitialized(ServletContextEvent event) {
        this.contextLoader = this.createContextLoader();
        if(this.contextLoader == null) {
            this.contextLoader = this;
        }

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

listener 节点存放的另一个类 RequestContextListener 实现了接口 ServletRequestListener,会监听每次 HTTP 请求,管理作用域为 Request 的 bean。对于作用域为 request 的 bean,就会在请求进来的时候创建,结束的时候销毁。

public interface ServletRequestListener extends EventListener {
    void requestDestroyed(ServletRequestEvent var1);
    void requestInitialized(ServletRequestEvent var1);
}

这其中 ContextLoaderListener 是必须的,RequestContextListener 是可选的。

servlet 节点用于配置处理 HTTP 请求的 HttpServlet 实现类,具体处理哪些请求是配置在 servlet-mapping 里的。DispatcherServlet 实现的是 MVC 模式中的控制器,负责分发请求。所有的 Web 请求都需要经过它来处理,进行转发、匹配、数据处理后,转由页面进行呈现。在初始化时会解析 contextConfigLocation 参数配置的文件,建立 MVC 子容器。

filter 节点配置过滤器 Filter,可以对 HTTP 请求做一些过滤、校验、日志监控记录的工作,具体适配的请求 url 配置在 filter-mapping 节点。

applicationContext.xml

ContextLoaderListener 会解析 applicationContext.xml 文件来初始化 Spring 容器。常见的配置示例如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-3.0.xsd" default-autowire="byName">
    <!-- 加载参数配置 -->
    <context:property-placeholder location="classpath:config.properties" ignore-unresolvable="true"/>

    <!-- 自动扫描 web 包 ,将带有注解的类 纳入 spring 容器管理 -->
    <context:component-scan base-package="com.xxx.web">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!-- 创建 bean -->
    <bean id="httpClient" class="com.xxx.http.HttpClient"/>

    <!-- 声明自动为spring容器中那些配置 @AspectJ 切面的 bean 创建代理 -->
    <aop:aspectj-autoproxy/>

    <!-- 加载其他配置文件,import 的使用使得配置文件也可以模块化 -->
    <import resource="classpath:xxx.xml"/>
</beans>

我有一个疑问,为什么要在 component-scan 里 exclude 掉 Controller 呢?这是因为 Spring 核心模块并不处理 HTTP 请求,处理 HTTP 请求的是 Spring MVC 子模块,两者使用的是不同的容器:Spring Context 父容器和 Spring MVC 子容器。Controller 注解的 bean 要在 mvc 容器中创建才能起到作用,所以要在父容器的配置中排除掉。

在 《Spring 技术内幕》这本书中提到“IOC 容器会首先向其双亲上下文去 getBean”,这跟我们日常运行程序的感受不符,所以到底是先去父容器拿 bean 还是先去子容器拿 bean,我们还是深入源码看看吧。ApplicationContext 的 getBean 方法实现在 AbstractApplicationContext 类:

public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext, DisposableBean {
    public <T> T getBean(Class<T> requiredType) throws BeansException {
        return this.getBeanFactory().getBean(requiredType);
    }
}

该方法调用了 BeanFactory 的 getBean 方法,从 AbstractBeanFactory 类的 getBean 方法中看到,的确是优先使用子容器的 bean:

    public Object getBean(String name) throws BeansException {
        return this.doGetBean(name, (Class)null, (Object[])null, false);
    }
    protected <T> T doGetBean(String name, Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException {
        final String beanName = this.transformedBeanName(name);
        Object sharedInstance = this.getSingleton(beanName);
        Object bean;
        if(sharedInstance != null && args == null) {
            // 省略
        } else {
            if(this.isPrototypeCurrentlyInCreation(beanName)) {
                throw new BeanCurrentlyInCreationException(beanName);
            }

            BeanFactory ex = this.getParentBeanFactory();
            // containsBeanDefinition 返回 false,即当前容器不存在 bean,才去父容器获取
            if(ex != null && !this.containsBeanDefinition(beanName)) {
                String var21 = this.originalBeanName(name);
                if(args != null) {
                    return ex.getBean(var21, args);
                }

                return ex.getBean(var21, requiredType);
            }
            // 省略其他。。。
    }

    private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap();
    // 此方法在 DefaultListableBeanFactory 类中
    public boolean containsBeanDefinition(String beanName) {
        Assert.notNull(beanName, "Bean name must not be null");
        return this.beanDefinitionMap.containsKey(beanName);
    }    

mvc.xml

spring mvc 子容器初始化依赖 mvc.xml,此文件具体名称是和 DispatcherServlet 配置在一起的参数。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-3.2.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    <!-- 扫描 Controller -->
    <context:component-scan base-package="com.xxx.controller" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
    </context:component-scan>
    <!-- HTTP 请求适配器 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <!-- 使用 Jackson 的 ObjectMapper 读取/编写 JSON 数据。它转换媒体类型为 application/json 的数据。 -->
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
            </list>
        </property>
    </bean>

    <!-- 配置 velocity 引擎 -->
    <bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
        <property name="resourceLoaderPath" value="/WEB-INF/views/vm/" />
        <property name="configLocation" value="classpath:velocity.properties" />
    </bean>

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="ignoreAcceptHeader" value="true"/>
        <property name="mediaTypes">
            <map>
                <entry key="json" value="application/json" />
                <entry key="xml" value="application/xml" />
                <entry key="jsonp" value="application/javascript" />
            </map>
        </property>
        <property name="favorParameter" value="false"/>
        <property name="viewResolvers">
            <list>
                <!-- vm 视图解析器 -->
                <bean id="velocityViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
                    <property name="suffix" value=".vm" />
                </bean>
                <!-- jsp 视图处理器 -->
                <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
                    <property name="prefix" value="/WEB-INF/views/jsp/"/>
                    <property name="suffix" value=".jsp"/>
                </bean>
                <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
            </list>
        </property>
        <property name="defaultViews">
            <list>
                <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
            </list>
        </property>
    </bean>

    <mvc:interceptors>
        <mvc:interceptor>
            <!-- 对所有的请求使用 CommonInterceptor 处理 -->
            <mvc:mapping path="/**" />
            <bean class="com.xxx.web.interceptor.CommonInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

此处的 component-scan 中要排除掉 Service 注解,那么如果不排除会有什么问题吗?多数情况下也不会有问题,但是如果你用到了 AOP,那么由于这里没有排除 Service 注解,Controller 用到的 Service 既会出现在父容器,也会出现在子容器,但是只有父容器中的 Service 会被 AOP 处理,然而 Controller 优先使用同一个容器中的 Service,就会导致其调用了没有被 AOP 代理的服务。

总结一下,mvc.xml 里存放的基本都是跟处理 HTTP 请求相关的配置。

参考资料

  1. 关于XML文档的xmlns、xmlns:xsi和xsi:schemaLocation
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容