小编典典

如何将Csv MimeType添加到Spring内容协商中?

spring-mvc

我正在创建一个可以提供xml,json和csv输出的webservice方法:

@GetMapping(produces = {APPLICATION_XML_VALUE, APPLICATION_JSON_VALUE, "text/csv"})
public Rsp get() {
}

问题:我不知何故需要将text/csv内容类型添加到configureContentNegotiation()。但是如何?因为不接受字符串,并且字符串MediaType.TEXT_CSV不存在(即使RFC7111将其定义为有效的模仿类型)。

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

阅读 320

收藏
2020-06-01

共1个答案

小编典典

.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
2020-06-01