2016-06-27 174 views
0

在Spring MVC配置文件中我有这样几个部分:春季控制器两次

<bean id="handler" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" 
      p:alwaysUseFullPath="true" 
      p:contentNegotiationManager-ref="contentNegotiationManager" 
      p:useRegisteredSuffixPatternMatch="true" /> 

<mvc:annotation-driven /> 

<context:annotation-config/> 

<context:component-scan base-package="com.tarhun.geo" use-default-filters="false"> 
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> 
</context:component-scan> 

的问题是,控制器映射在日志中注册了两次,也就是我看到每个映射消息重复:

annotation.RequestMappingHandlerMapping:217 - 映射“{[/ rest/company/{companyId}]”,遇见hods = [],params = [],heade ....

我觉得问题在那个自定义RequestMappingHandlerMapping的定义中。因为我删除它 - 我的控制器只映射一次。但我仍然需要它,因为如果我删除它,我试图调用API时得到异常:No mapping found...

您能否请建议一些?我也有其他Spring上下文配置文件,但我确定他们没有加载控制器第二次(我甚至使用context:exclude=Controller来防止这种情况)。

+0

,还有应该是默认的映射处理。 –

+0

@RomanC好的,我会尝试删除它。但是,我仍然有点困惑它是如何成为问题的?据我了解所有这些做第一个配置节(我们声明'handler' bean) - 它只是配置'RequestMappingHandlerMapping'单例。后来这个配置的bean应该在Spring内部使用。 – MyTitle

回答

1

在你的mvc配置中,组件被扫描两次,你不需要那样做。

在配置中,您可以设置注释驱动的配置,并且您的xml配置应该如下所示。

<aop:aspectj-autoproxy /> 

<mvc:annotation-driven> 
    <mvc:message-converters> 
     <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/> 
     <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"/> 
     <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> 
    </mvc:message-converters> 
</mvc:annotation-driven> 

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

<!-- UI resources exclusions from servlet mapping --> 
<mvc:resources location="/ui/" mapping="/ui/**"/> 

添加包含/排除过滤器是可选的,如果你只是想加载你不需要它控制器,服务或信息库

+0

为什么他们被扫描两次?由于'RequestMappingHandlerMapping'? – MyTitle

+1

是的。 请阅读[RequestMappingHandlerMapping](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.html)文档。它总是扫描Controller和RequestMapping并生成RequestMappingInfo对象。如果您在xml中配置注释驱动的扫描,则不需要执行此操作。 –