1

如果我将组件扫描放在 spring-common.xml 中并且 Spring MVC 找不到控制器,为什么?但是如果我将组件扫描放在 springMVC-servlet.xml 中并且它可以工作。

web.xml

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

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:spring/spring-*.xml</param-value>
</context-param>


<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>


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

springMVC-servlet.xml

<mvc:annotation-driven />


<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="order" value="2" />
    <property name="prefix" value="/WEB-INF/view/" />
    <property name="suffix" value=".html" />
</bean>

<!-- 对静态资源文件的访问 -->
<mvc:resources mapping="/js/**" location="/static/js/" />
<mvc:resources mapping="/css/**" location="/static/css/" />
<mvc:resources mapping="/image/**" location="/static/image/" />
<mvc:default-servlet-handler />

spring-common.xml

<context:component-scan base-package="com.wind">
</context:component-scan>

4

1 回答 1

0

即使您将 spring-common.xml 保留在项目中。您的容器(Tomcat、Jboss)将在它们可访问时识别它们。似乎容器无法访问。

它可以通过两种方式完成。

1) 将您的 spring-common,xml 包含到 web.xml 的上下文配置位置,如下所示

<init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/springMVC-servlet.xml</param-value>
        <param-value>classpath:spring/spring-common.xml</param-value>
 </init-param>

2) 从 springMVC-servlet.xml 导入 sprin-common.xml

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="order" value="2" />
    <property name="prefix" value="/WEB-INF/view/" />
    <property name="suffix" value=".html" />
</bean>

<import resource="spring-common.xml"/>

http://www.mkyong.com/spring/load-multiple-spring-bean-configuration-file/

于 2016-07-02T18:04:22.397 回答