【问题标题】:What is the WebMvcConfigurationSupport replacement in Spring Boot?Spring Boot 中的 WebMvcConfigurationSupport 替换是什么?
【发布时间】:2016-05-10 05:58:18
【问题描述】:

在传统的 Spring MVC 中,我可以扩展 WebMvcConfigurationSupport 并执行以下操作:

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.favorPathExtension(false).
    favorParameter(true).
    defaultContentType(MediaType.APPLICATION_JSON).
    mediaType("xml", MediaType.APPLICATION_XML);
}

如何在 Spring Boot 应用程序中执行此操作?我的理解是添加 WebMvcConfigurationSupport@EnableWebMvc 会禁用 Spring Boot WebMvc 自动配置,这是我不想要的。

【问题讨论】:

    标签: spring-mvc spring-boot content-negotiation


    【解决方案1】:

    auto configuration and Spring MVC 上的每个 Spring Boot 参考:

    如果你想完全控制 Spring MVC,你可以添加你自己的带有 @EnableWebMvc 注解的 @Configuration。如果您想保留 Spring Boot MVC 功能,并且只想添加额外的 MVC 配置(拦截器、格式化程序、视图控制器等),您可以添加自己的 WebMvcConfigurerAdapter 类型的 @Bean,但不添加 @EnableWebMvc。

    比如你想保留Spring Boot的自动配置,自定义ContentNegotiationConfigurer:

    @Configuration
    public class WebMvcConfig extends WebMvcConfigurerAdapter {
    
       ...
       @Override
       public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
          super.configureContentNegotiation(configurer);
          configurer.favorParameter(..);
          ...
          configurer.defaultContentType(..);
       }
    }
    

    【讨论】:

    • 你说得对,我知道,但我目前扩展的类不是WebMvcConfigurerAdapter,而是WebMvcConfigurationSupport。后者提供了前者没有的配置选项。
    • 我认为不可能使用 Spring Boot 的 WebMvcAutoConfiguration 的任何部分并提供您自己的 WebMvcConfigurationSupport,因为 Spring Boot 只有在没有 WebMvcConfigurationSupport 的情况下才会自动配置。我认为使用 Spring Boot 的优点之一是自动配置。我会尝试使用 WebMvcConfigurerAdapter,对于不支持的选项,请使用某种 BeanPostProcessor 手动自定义它。
    • 我会试试的。由于您的答案不完全是我想要的,我现在不接受它,但我会支持它。如果解决了,我稍后会接受你的回答。
    • 嗨@ikumen 我已经尝试过这个配置,但是我的其他MVC配置是基于XML的,所以我收到这个错误:Error created bean with name 'resourceHandlerMapping' defined in class path resource [com/ecc/ws/rest/config/WebConfig.class]:通过工厂方法进行 Bean 实例化失败;嵌套异常是 org.springframework.beans.BeanInstantiationException:无法实例化 [org.springframework.web.servlet.HandlerMapping]:工厂方法“resourceHandlerMapping”抛出异常;嵌套异常是 java.lang.IllegalStateException: No ServletContext set
    【解决方案2】:

    从 Spring 5.0 开始,您可以使用接口 WebMvcConfigurer,因为 Java 8 允许在接口上实现默认实现。

    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
    
       ...
       @Override
       public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
          configurer.favorParameter(..);
          ...
          configurer.defaultContentType(..);
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      • 2018-09-20
      • 2019-01-13
      • 1970-01-01
      相关资源
      最近更新 更多