如何理解SpringMVC资源链包括我没有设置的解析器

时间:2016-12-14 06:12:18

标签: spring-mvc static-resource

我的dispatcher.xml设置如下资源链:

<mvc:resources location="/static/" mapping="/static/**" cache-period="31536000">
        <mvc:resource-chain resource-cache="true">
            <mvc:resolvers>
                <!--<bean class="org.springframework.web.servlet.resource.GzipResourceResolver"/>-->
                <bean class="org.springframework.web.servlet.resource.CachingResourceResolver">
                    <constructor-arg ref="staticResourceCache"/>
                </bean>
                <bean class="org.springframework.web.servlet.resource.VersionResourceResolver">
                    <property name="strategyMap">
                        <map>
                            <entry key="/**">
                                <bean class="org.springframework.web.servlet.resource.ContentVersionStrategy"/>
                            </entry>
                        </map>
                    </property>
                </bean>
                <bean class="org.springframework.web.servlet.resource.PathResourceResolver"/>
            </mvc:resolvers>
            <mvc:transformers>
                <bean class="org.springframework.web.servlet.resource.CachingResourceTransformer">
                    <constructor-arg ref="staticResourceCache"/>
                </bean>
                <bean class="org.springframework.web.servlet.resource.CssLinkResourceTransformer">
                    <!--<property name="allowedLocations" value="/static"> </property>-->
                </bean>
            </mvc:transformers>
        </mvc:resource-chain>
    </mvc:resources>

当我调试代码时,我发现资源链有两个PathResourceResolver,为什么?谢谢! ResourceHttpRequestHanndler state

2 个答案:

答案 0 :(得分:0)

我怀疑Spring正在添加一个默认PathResourceResolver bean,其默认标识为pathResourceResolver。你明确宣布一个但没有id,所以你最终得到2.
Spring框架做了很多 - 即。它会为你创建默认bean,除非你指定一个具有相同id的bean。

你可以通过以下方式测试这个理论:
1)评论你的PathResourceResolver你的配置?你最终得到1?
2)在您的配置中使用您的PathResourceResolver,但是为其指定pathResourceResolver?你最终得到1?

答案 1 :(得分:0)

我刚刚发现spring-mvc-4.3.xsd中存在注释:

<xsd:documentation source="org.springframework.web.servlet.config.annotation.ResourceChainRegistration"><![CDATA[
Assists with the registration of resource resolvers and transformers.
Unless set to "false", the auto-registration adds default Resolvers (a PathResourceResolver) and Transformers
(CssLinkResourceTransformer, if a VersionResourceResolver has been manually registered).
The resource-cache attribute sets whether to cache the result of resource resolution/transformation;
setting this to "true" is recommended for production (and "false" for development).
A custom Cache can be configured if a CacheManager is provided as a bean reference
in the "cache-manager" attribute, and the cache name provided in the "cache-name" attribute.
        ]]></xsd:documentation>