我开始从基于 XML 的配置转向 @EnableWebMvc 和 WebMvcConfigurerAdapter 配置。但是当我更改配置时,它似乎从 DefaultAnnotationHandlerMapping 切换到 RequestMappingHandlerAdapter。
如果我想切换回 DefaultAnnotationHandlerMapping,我该如何设置?
(我知道 DefaultAnnotationHandlerMapping 已被弃用,但我仍然想知道如何设置 spring 来使用它)
最佳答案
Adding this annotation to an
@Configuration
class imports the Spring MVC configuration fromWebMvcConfigurationSupport
[...]
This class registers the following
HandlerMappings
:
RequestMappingHandlerMapping
ordered at 0 for mapping requests to annotated controller methods.HandlerMapping
ordered at 1 to map URL paths directly to view names.BeanNameUrlHandlerMapping
ordered at 2 to map URL paths to controller bean names.HandlerMapping
ordered atInteger.MAX_VALUE-1
to serve static resource requests.HandlerMapping
ordered atInteger.MAX_VALUE
to forward requests to the default servlet.
这就是 RequestMappingHandlerMapping
的来源。这个“默认”配置或多或少相当于指定
<mvc:annotation-driven />
在 XML 配置中。
如果您想在 RequestMappingHandlerMapping
之前(按顺序)声明一个 DefaultAnnotationHandlerMapping
,则为其声明您自己的 bean 并将其顺序设置得较低。
@Bean
public DefaultAnnotationHandlerMapping defaultAnnotationHandlerMapping() {
DefaultAnnotationHandlerMapping defaultAnnotationHandlerMapping = new DefaultAnnotationHandlerMapping();
defaultAnnotationHandlerMapping.setOrder(-1);
// and other properties
return defaultAnnotationHandlerMapping;
}
如果您希望它成为在 DispatcherServlet
中注册的唯一 HandlerMapping
,则将该 bean 命名为 “handlerMapping”
并设置 DispatcherServlet#detectAllHandlerMappings
属性设置为false
。
关于java - 使用 DefaultAnnotationHandlerMapping 进行 Spring @EnableWebMvc 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40492467/