【问题标题】:How to set detectHandlerMethodsInAncestorContexts true?如何设置detectHandlerMethodsInAncestorContexts true?
【发布时间】:2015-11-26 14:49:42
【问题描述】:

在spring-webmvc中,AbstractHandlerMethodMapping.java中有一个参数detectHandlerMethodsInAncestorContexts

它的默认值为假。我怎样才能设置它为真?

【问题讨论】:

  • 有人可以帮我吗?
  • 问题是我想将@Controller添加到webmvc的父上下文(由ContextLoaderListener构建),但是我发现AbstractHandlerMethodMapping(Spring-webmvc的源)中有一个名为detectHandlerMethodsInAncestorContexts的文件,只有当布尔值是真的,springmvc 虽然处理父上下文的控制器,但我找不到在哪里设置它。
  • 改进了语法、格式并链接到 Spring 文档。
  • 请考虑共享您的代码,以便我们能够看到您尝试将其设置为 true 的上下文。

标签: spring spring-mvc controller


【解决方案1】:

只需显式创建RequestMappingHandlerMapping bean 并将此值设置为true

@Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
    RequestMappingHandlerMapping requestMappingHandlerMapping = new RequestMappingHandlerMapping();
    requestMappingHandlerMapping.setDetectHandlerMethodsInAncestorContexts(true);
    return requestMappingHandlerMapping;
}

【讨论】:

    【解决方案2】:

    在 Spring 4(Boot 1.5)中,这对我有用:

    @Configuration
    @ComponentScan(basePackages = "my.app")
    class WebpageContext extends WebMvcConfigurationSupport {
        @Override
        protected RequestMappingHandlerMapping createRequestMappingHandlerMapping() {
           RequestMappingHandlerMapping mapping = new RequestMappingHandlerMapping();
           mapping.setDetectHandlerMethodsInAncestorContexts(true); 
           return mapping;
        }
    }
    

    (通常您使用@EnableWebMvc 注释您的@Configuration 类并扩展@WebMvcConfigurerAdapter,但它不会公开请求映射,因此我们需要直接扩展WebMvcConfigurationSupport。)

    【讨论】:

      猜你喜欢
      • 2018-11-03
      • 2020-08-28
      • 2020-02-26
      • 1970-01-01
      • 2021-12-17
      • 2012-01-18
      • 2016-02-05
      • 2020-06-04
      • 2010-12-12
      相关资源
      最近更新 更多