You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

引入Azure Blob存储库导致Spring接口返回XML如何兼容解决

问题核心矛盾

冲突源于两个特性的叠加:

  1. Azure Storage Blob SDK 运行必须依赖 jackson-dataformat-xml 包,无法直接排除
  2. Spring Boot 会自动检测 classpath 下的 jackson-dataformat-xml 组件,自动注册 XML 消息转换器,导致接口默认返回优先级变更为XML优先

解法一:调整Spring MVC内容协商默认优先级(最推荐)

无需修改任何依赖,仅通过配置调整Spring MVC的默认返回格式为JSON,同时保留XML响应能力,完全不影响Azure SDK运行。

配置文件方式(applicaiton.yml)

spring:
  mvc:
    content-negotiation:
      default-content-type: application/json
      media-types:
        json: application/json
        xml: application/xml

配置文件方式(application.properties)

spring.mvc.content-negotiation.default-content-type=application/json
spring.mvc.content-negotiation.media-types.json=application/json
spring.mvc.content-negotiation.media-types.xml=application/xml

Java配置方式

import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(MediaType.APPLICATION_JSON);
    }
}

解法二:移除Spring自动注册的XML消息转换器

如果业务完全不需要支持XML格式的响应,可以直接从Spring的消息转换器列表中删除XML转换器,jackson-dataformat-xml 包依旧保留给Azure SDK调用:

import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.removeIf(converter -> converter instanceof MappingJackson2XmlHttpMessageConverter);
    }
}

两种方案都不需要对azure-storage-blob的依赖做排除配置,保留原始依赖即可,Azure SDK可以正常调用XmlMapper相关类,不会出现NoClassDefFoundError错误。

内容的提问来源于stack exchange,提问作者pennstatephil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 16:06:03