【发布时间】:2019-03-22 05:41:48
【问题描述】:
我正在构建一个带有多个端点的 Spring Boot 服务。我的服务需要同时支持json 和xml 输出。大多数端点将仅是json,而一些端点将仅是xml。我可以使用注释@RequestMapping 指定特定端点接受或返回的内容类型。例如:
@RequestMapping(method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_XML_VALUE},
produces = {MediaType.APPLICATION_XML_VALUE})
但是,由于我的应用程序的大多数端点仅是 json,我想避免编写
consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE}
在所有这些中。有没有办法让用@RequestMapping 注释的方法具有默认的consumes 和produces 媒体类型?每当我需要不同于默认值的东西时,我都可以指定它。
我已尝试设置内容协商,但不适用于此。我认为我可以通过自定义ContentNegotiationStrategy 的内容协商来做到这一点,但我需要该代码才能读取该请求的处理程序的注释(用@RequestMapping 注释的特定方法)和代码只得到一个NativeWebRequest。
是否有用于实现此目的的全局 Spring 配置?
编辑: 设置内容协商
@Configuration
@EnableWebMvc
class ContentNegotiationConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorParameter(false)
.favorPathExtension(true)
.ignoreAcceptHeader(true)
.ignoreUnknownPathExtensions(false)
.useJaf(false)
.defaultContentType(MediaType.APPLICATION_JSON);
}
}
和端点
@RequestMapping(method = RequestMethod.GET)
然后调用端点
GET https://localhost:8080/endpoint.xml
返回 xml 输出和 HTTP 200 而不是 HTTP 406。
【问题讨论】:
标签: java spring spring-boot