SpringBoot REST 项目, 默认返回类型为 JSON. 可是为了兼容老项目调用默认返回XML, 因此须要设置默认类型为XML.html
默认设置为XML之后, 客户端依然能够设置 http header, 的 Accept
为 application/json
, SpringBoot 将会正常返回 JSON 数据.git
设置方法以下:github
/** * 将默认 content-type 设置为 XML <br/> * * 参考: <br/> * * http://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/content-negotiation-default-media-type/ * <br/> * * https://stackoverflow.com/questions/33009918/spring-boot-controller-content-negotiation */ @Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.defaultContentType(MediaType.TEXT_XML); } // 下面解决因在SpringBoot项目中使用 @EnableWebMvc 注解, 而没法使用 swagger-ui 的问题 @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { /** * Setup Swagger UI <br/> * refer: https://github.com/springfox/springfox/issues/1427 */ registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/", "classpath:/META-INF/resources/images"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
SpringBoot 要支持 XML 序列化须要引入 Jackson 的 XML 支持, 参考: http://www.javashuo.com/article/p-bohltosn-ht.htmlweb
同时使用swagger注意, 在 SpringBoot 项目中, 若是使用
@EnableWebMvc
注解, 会影响 SpringBoot 的一些加载, 而致使 swagger ui 没法使用. 因此上面添加了相应的 ResourceHandler 去解决这个问题.spring