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 去解决这个问题.

转载于:https://my.oschina.net/u/1169457/blog/1578237

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值