美文网首页Spring boot
Swagger2异常:Illegal DefaultValue

Swagger2异常:Illegal DefaultValue

作者: 三也视界 | 来源:发表于2020-11-20 09:35 被阅读0次

对于集成Swagger(2.9.2版本,其他版本没有验证是否存在该问题),搭建Spring boot基本架构,请查看之前的文章,这里直接分析Swagger的bug
SpringBoot+MyBatis搭建SSM基本骨架(Redis + Swagger+自定义配置 +mysql )

之前测试一直用postman,直到打开http://localhost:5088/swagger-ui.htm才发现存在bug

一、异常分析:
Illegal DefaultValue null for parameter type integerNumberFormatException: For input string: ""

从上面这句可以看出,有个默认值是空字符串的变量转换成Integer类型时异常。


image.png

根据上面这句报错信息,点进去AbstractSerializableParameter.java:412可以看到

if(BaseIntegerProperty.TYPE.equals(type)){

return Long.valueOf(example);

}

就是说如果实体属性类型是Integer,就把example转为Long类型,而example默认为"",导致转换错误。

二、解决办法:

我们知道,在Swagger的浏览器界面打开的时候,对上述的默认值解析错误。一般情况下我们都省略了实体类上加@ApiModelProperty。因此解决这个问题可以在实体类中的Integer类型的属性添加注解,并给example参数赋值,且值必须为数字类型。

@ApiModelProperty(value = "试卷ID",example = "1")
private int pageId;

如果每个值都需要添加,那么会很多。
所以下面是第二种办法。我们知道报错的是at io.swagger.models.parameters.AbstractSerializableParameter.getExample(AbstractSerializableParameter.java:412) ~[swagger-models-1.5.20.jar:1.5.20]

查看pom.xml我们引用的是springfox的包,找到github项目# springfox/springfox

issue查询swagger-models-1.5.20.jar,查看前面几天issue,可以发现有人已经给出了解决方案


image.png

比如https://github.com/springfox/springfox/issues/2265

image.png
可以看到上面的解决方案是比较靠谱的,点赞的人数较多。从log我们就可以看出swagger-models-1.5.20报错了,而1.5.21版本解决了这个问题,所以更换引用即可
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
<!--移除swagger-models 1.5.20 依赖,存在Swagger2异常:Illegal DefaultValue null for parameter type integer问题-->
    <exclusions>
        <exclusion>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
        </exclusion>
        <exclusion>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>1.5.21</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-models</artifactId>
    <version>1.5.21</version>
</dependency>

相关文章

网友评论

    本文标题:Swagger2异常:Illegal DefaultValue

    本文链接:https://www.haomeiwen.com/subject/ljakiktx.html