繁体   English   中英

基于Spring注释的配置中的mvc:default-servlet-handler的等价物?

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

是否可以在AnnotationConfig(Web)ApplicationContext定义等效的<mvc:default-servlet-handler/> 现在我有:

@Configuration
@ImportResource("classpath:/mvc-resources.xml")
class AppConfig {
  // Other configuration...
}

在我的resources/mvc-resources.xml只有以下内容:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:default-servlet-handler/>
</beans>

它按预期工作。 是否可以在不导入XML文件的情况下执行此操作? 这将是一个减少一些样板的好方法。

如果您将Spring 3.1与WebMvc一起使用,则可以配置默认的servlet处理,如下所示:

@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureDefaultServletHandling(
            DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

在深入挖掘之后,我发现这是一个已知问题,并在即将到来的Spring 3.1中通过注释功能解决。

我用以下代码解决了我的问题:

@Configuration
@Import(FeatureConfig.class)
class AppConfig {
   ...
}

@FeatureConfiguration
class FeatureConfig {
  @Feature
  public MvcDefaultServletHandler defaultHandler() {
    return new MvcDefaultServletHandler();
  }
}

这确实需要使用spring的里程碑版本,但它似乎是最清洁和首选的处理方式。

我不认为你可以开箱即用,但你可以复制DefaultServletHandlerBeanDefinitionParser所做的事情 :创建一个类型为DefaultServletHttpRequestHandler的Bean并将其映射到URL方案/**

我会说你的Bean应该是DefaultServletHttpRequestHandler子类,并@PostConstruct方法中进行映射。

@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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM