为了账号安全,请及时绑定邮箱和手机立即绑定

如果使用 WebMvcConfigurationSupport 添加转换器

如果使用 WebMvcConfigurationSupport 添加转换器

宝慕林4294392 2023-10-12 14:46:10
我有一个带有 swagger 文件的 springboot 应用程序。我使用任何 swagger Maven 插件并且它可以工作。我的 pom.xml 文件:    <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>我使用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;  }}我有这个错误:"Failed to convert value of type 'java.lang.String' to required type 'com.foo.TempReadingSource';所以我在 Springboot2 配置中添加了一个转换器:@Configurationpublic class StrubConfig extends WebMvcConfigurationSupport {    @Override    public FormattingConversionService mvcConversionService() {        FormattingConversionService f = super.mvcConversionService();        f.addConverter(new TempReadingSourceConverter());        return f;    }}和:public class TempReadingSourceConverter implements Converter<String, TempReadingSource> {    @Override    public TempReadingSource convert(String source) {       try {          return TempReadingSource.fromValue(source);       } catch(Exception e) {          return null;       }    }}这Converter解决了我的 API(通过邮递员)但现在swagger-ui找不到:
查看完整描述

1 回答

?
白板的微信

TA贡献1883条经验 获得超3个赞

解决方案是:


@Configuration

public class StrubConfig {


    @Autowired

    private FormattingConversionService conversionService;


    @PostConstruct

    public void registerCustomConverter() {

        conversionService.addConverter(new TempReadingSourceConverter());

    }


}



查看完整回答
反对 回复 2023-10-12
  • 1 回答
  • 0 关注
  • 94 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信