2

我正在开发一个应该启用 swagger-ui 的 Spring Boot 应用程序。访问http://localhost:8080/swagger-ui.html时弹出错误:“Unable to infer base url ...”

另外,http://localhost:8080/v2/api-docs显示:第 1 行第 1 列的错误:文档为空 此页面的源代码是 json,但请求为 Content-Type application/xhtml+ xml;charset=UTF-8

造成这种情况的原因似乎是我的自定义杰克逊配置:

@Configuration
public class JacksonConfig {

@Bean
public MappingJackson2XmlHttpMessageConverter mappingJackson2XmlHttpMessageConverter() {
    return new MappingJackson2XmlHttpMessageConverter(objectMapper());
}

@Bean
public ObjectMapper objectMapper() {
    JacksonXmlModule xmlModule = new JacksonXmlModule();
    xmlModule.setDefaultUseWrapper(false);
    XmlMapper objectMapper = new XmlMapper(xmlModule);
    objectMapper
            .registerModule(new ParameterNamesModule())
            .registerModule(new Jdk8Module())
            .registerModule(new JavaTimeModule());
    objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
    objectMapper
            .configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false)
            .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);

    return objectMapper;
}
}

具有以下依赖项:

<dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
    </dependency>

问题也在这里描述:https ://github.com/springfox/springfox/issues/1835

所以我的问题是:如何指定杰克逊消息转换器的优先级以使 swagger-ui 工作?

4

2 回答 2

0

我只是在重新阅读自己的问题时偶然发现了解决方案。

只需将其添加到上面的 JacksonConfig 类中(不知道排序是否重要,但它有效)。

@Bean
public MappingJackson2HttpMessageConverter jsonConverter() {
    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    ObjectMapper objectMapper = new ObjectMapper();
    jsonConverter.setObjectMapper(objectMapper);
    return jsonConverter;
}
于 2018-04-10T12:44:21.137 回答
0

在 swagger 代码中,它会检查 ObjectMapper 是否存在,如果不存在,它会创建一个来使用。如果创建了一个使用 ObjectMapper 或 XMLMapper 的 bean,那么 Swagger 将使用这个实例,并被破坏。解决方法是为 ObjectMapper 创建一个 bean 并使用 @Primary 注释,然后创建您要使用的 XMLMapper bean。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@Configuration
public class MessageResponseXMLMapper {


      @Bean
      @Primary
      public ObjectMapper customObjectMapper() {
            return new ObjectMapper();
      }


      @Bean(name="customXmlMapper")
      public XmlMapper customXmlMapper() {
            return new Jackson2ObjectMapperBuilder()
                    .indentOutput(true)
                    .createXmlMapper(true)
                    .propertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE)
                    .build();     }   

}

希望这可以帮助

于 2019-08-16T13:56:55.680 回答