简体   繁体   中英

Swagger OpenAPI 3 not display on springboot 2 if add Converter with a WebMvcConfigurationSupport

I have a springboot application with swagger file. I use any swagger Maven plugin and it works.

在此处输入图像描述

My pom.xml file:

    <dependency>
        <groupId>io.swagger.core.v3</groupId>
        <artifactId>swagger-core</artifactId>
        <version>2.0.9</version>
    </dependency>
    <dependency>
        <groupId>io.swagger.core.v3</groupId>
        <artifactId>swagger-annotations</artifactId>
        <version>2.0.9</version>
    </dependency>
    <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-annotations</artifactId>
        <version>1.5.23</version>
    </dependency>
    <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-ui</artifactId>
        <version>1.1.45</version>
    </dependency>

I use an java enum :

public enum TempReadingSource {
  COLDROOM("coldroom"),
    LOCAL("local"),
    OVEN("oven");

  private String value;

  TempReadingSource(String value) {
    this.value = value;
  }

  @Override
  @JsonValue
  public String toString() {
    return String.valueOf(value);
  }

  @JsonCreator
  public static TempReadingSource fromValue(String text) {
    for (TempReadingSource b : TempReadingSource.values()) {
      if (String.valueOf(b.value).equals(text)) {
        return b;
      }
    }
    return null;
  }
}

and I have this error:

"Failed to convert value of type 'java.lang.String' to required type 'com.foo.TempReadingSource';

So I add a converter in my Springboot2 configuration:

@Configuration
public class StrubConfig extends WebMvcConfigurationSupport {

    @Override
    public FormattingConversionService mvcConversionService() {
        FormattingConversionService f = super.mvcConversionService();
        f.addConverter(new TempReadingSourceConverter());
        return f;
    }

}

and:

public class TempReadingSourceConverter implements Converter<String, TempReadingSource> {
    @Override
    public TempReadingSource convert(String source) {
       try {
          return TempReadingSource.fromValue(source);
       } catch(Exception e) {
          return null;
       }
    }
}

This Converter solve my API (via postman) but now swagger-ui is not found:

在此处输入图像描述

Solution is:

@Configuration
public class StrubConfig {

    @Autowired
    private FormattingConversionService conversionService;

    @PostConstruct
    public void registerCustomConverter() {
        conversionService.addConverter(new TempReadingSourceConverter());
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM