SpringBoot 默认 content-type 设置为 XML

SpringBoot REST 项目, 默认返回类型为 JSON. 但是为了兼容老项目调用默认返回XML, 所以需要设置默认类型为XML.

默认设置为XML以后, 客户端依然可以设置 http header, 的 Acceptapplication/json, SpringBoot 将会正常返回 JSON 数据.

设置方法如下:

/**
 * 将默认 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 支持, 参考: https://my.oschina.net/u/1169457/blog/1577238

同时使用swagger注意, 在 SpringBoot 项目中, 如果使用@EnableWebMvc 注解, 会影响 SpringBoot 的一些加载, 而导致 swagger ui 无法使用. 所以上面添加了相应的 ResourceHandler 去解决这个问题.

猜你喜欢

转载自my.oschina.net/u/1169457/blog/1578237