简体   繁体   中英

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

Is it possible to have the equivalent of <mvc:default-servlet-handler/> defined in an AnnotationConfig(Web)ApplicationContext ? Right now I have:

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

with just the following in my 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>

And it works as expected. Is it possible to do this without importing an XML file? It would be a nice way to cut down on some boilerplate.

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();
    }
}

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.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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