如何将Csv MimeType添加到Spring内容协商中?
问题描述:
我正在创建一个可提供xml,json和csv输出的网络服务方法:
I'm creating a webservice method that can serve xml, json and csv output:
@GetMapping(produces = {APPLICATION_XML_VALUE, APPLICATION_JSON_VALUE, "text/csv"})
public Rsp get() {
}
问题:我不知何故需要将 text / csv
内容类型添加到我的 configureContentNegotiation()
中。但是如何?因为不接受字符串,并且 MediaType.TEXT_CSV
不存在(即使 RFC7111 将其定义为有效的模仿类型。
Problem: I somehow need to add the text/csv
content type to my configureContentNegotiation()
. But how? Because a String is not accepted, and a MediaType.TEXT_CSV
does not exist (even though RFC7111 defines it as a valid mimetype.
@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.favorParameter(true)
.mediaType("json", MediaType.APPLICATION_JSON)
.mediaType("xml", MediaType.APPLICATION_XML)
.mediaType("csv", "text/csv"); //this is invalid
}
}
答
.mediaType("csv", new MediaType("text", "csv"));
甚至配置在 application.properties
中如下:
spring.mvc.media-types.json=application/json
spring.mvc.media-types.xml=application/xml
spring.mvc.media-types.csv=text/csv