【问题标题】:XML as a default response for Spring RestXML 作为 Spring Rest 的默认响应
【发布时间】:2018-09-10 09:04:52
【问题描述】:

我正在使用 Spring Boot 创建 REST 服务,当未收到来自客户端的 Accept 标头时,该服务必须默认返回 application/XML 作为响应。不幸的是,Spring 默认使用 JSON。如何切换此默认行为?

到目前为止我已经尝试过:

添加此依赖项有助于生成 XML(但仅使用客户端设置的 Accept 标头 - 因此没有默认值):

<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

尝试在我的@SpringBoot 类中为ContentNegotiationManagerFactoryBean 设置默认值

 @Bean
  ContentNegotiationManagerFactoryBean contentNegotiationManagerFactoryBean() {
    val myBean = new ContentNegotiationManagerFactoryBean();
    myBean.setDefaultContentType(MediaType.APPLICATION_XML);
    return myBean;
  }

导致错误:

org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter 中的方法 viewResolver 需要一个 bean,但找到了 2 个

试图通过以下方式排除它:

@SpringBootApplication(exclude = { ContentNegotiationManagerFactoryBean.class })

只给出另一个错误:

无法排除以下类,因为它们不是自动配置类

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    您可以使用ContentNegotiationConfigurer 来设置默认内容类型,而不是创建自己的ContentNegotiationManagerFactoryBean

    在您的WebMvcConfigurerAdapter 中,覆盖方法configureContentNegotiation() 并在提供的ContentNegotiationConfigurer 上调用方法defaultContentType()。这样,自动配置的ContentNegotiationManager 将设置该选项。

    【讨论】:

    • 谢谢,这就是我要找的。一些注意事项 - WebMvcConfigurerAdapter 已被弃用,因此我使用在我的 SpringBootApplication 中实现 WebMvcConfigurer。
    • 哦,是的,我不知何故认为 Spring 4.x/Spring Boot 1.x 不知道为什么。
    猜你喜欢
    • 2022-01-23
    • 2020-10-18
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 2023-02-17
    • 2015-05-20
    相关资源
    最近更新 更多