Equivalent of mvc:default-servlet-handler in Spring annotation-based configuration?

后端 未结 4 2399
野趣味
野趣味 2021-02-19 00:45

Is it possible to have the equivalent of defined in an AnnotationConfig(Web)ApplicationContext? Right now I have:<

相关标签:
4条回答
  • 2021-02-19 00:59

    After digging a bit deeper, I found out that this is a known problem and is addressed by annotation features in the upcoming Spring 3.1.

    I solved my problem with the following code:

    @Configuration
    @Import(FeatureConfig.class)
    class AppConfig {
       ...
    }
    
    @FeatureConfiguration
    class FeatureConfig {
      @Feature
      public MvcDefaultServletHandler defaultHandler() {
        return new MvcDefaultServletHandler();
      }
    }
    

    This does require using the milestone version of spring, though, but it seems to be the cleanest and preferred way of handling this.

    0 讨论(0)
  • 2021-02-19 01:06

    I don't think you can do it out of the box, but you can probably copy what DefaultServletHandlerBeanDefinitionParser does: Create a Bean of type DefaultServletHttpRequestHandler and map it to the URL scheme /**.

    I'd say your Bean should subclass DefaultServletHttpRequestHandler and do the mapping in a @PostConstruct method.

    0 讨论(0)
  • 2021-02-19 01:09

    If you are using Spring 3.1 with WebMvc, you can configure default servlet handling like this:

    @Configuration
    @EnableWebMvc
    public class MvcConfig extends WebMvcConfigurerAdapter {
    
        @Override
        public void configureDefaultServletHandling(
                DefaultServletHandlerConfigurer configurer) {
            configurer.enable();
        }
    }
    
    0 讨论(0)
  • 2021-02-19 01:14
    @Bean
    public DefaultServletHttpRequestHandler defaultServletHttpRequestHandler() {
      return new DefaultServletHttpRequestHandler();
    }
    
    @Bean
    public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
      Map<String, String> urlMap = new ManagedMap<String, String>();
      urlMap.put("/**", defaultServletHandlerName);
    
      SimpleUrlHandlerMapping hm = new SimpleUrlHandlerMapping();
      hm.setUrlMap(urlMap);
      return hm;
    }
    
    0 讨论(0)
提交回复
热议问题