在Spring Boot中集成Swagger2,使用@ApiImplicitParam注解时出现如下异常“Illegal DefaultValue 0 for parameter type integer”,异常详情如下:
代码语言:javascript复制Illegal DefaultValue 0 for parameter type integer
java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68) ~[na:na]
at java.base/java.lang.Long.parseLong(Long.java:709) ~[na:na]
at java.base/java.lang.Long.valueOf(Long.java:1151) ~[na:na]
at io.swagger.models.parameters.AbstractSerializableParameter.getExample(AbstractSerializableParameter.java:412) ~[swagger-models-1.5.20.jar:1.5.20]
相关源代码的写法如下:
代码语言:javascript复制/**
* 删除用户
*/
@ApiImplicitParams({
@ApiImplicitParam(name = "id",
value = "用户ID",
paramType = "path",
required = true,
dataType = "Long",
defaultValue = "0"),
@ApiImplicitParam(name = "remark", value = "备注")
})
@ApiOperation(value = "根据ID删除用户", tags = "删除")
@DeleteMapping("{id}")
public void delete(@PathVariable("id") Long id) {
userService.delete(id);
}
当使用@ApiImplicitParam时,针对id字段,使用了required=true和defaultValue=“0”的配置,但并不能解决该异常。而且异常的描述具有迷糊性,说什么“DefaultValue”类型非法。
其实仔细看异常中AbstractSerializableParameter.getExample相关代码,应该是example处理时导致了异常。于是在上面的属性中添加了example = "0"的属性。异常成功解决。正确代码如下:
代码语言:javascript复制/**
* 删除用户
*/
@ApiImplicitParams({
@ApiImplicitParam(name = "id",
value = "用户ID",
paramType = "path",
required = true,
dataType = "Long",
defaultValue = "0",
example = "0"),
@ApiImplicitParam(name = "remark", value = "备注")
})
@ApiOperation(value = "根据ID删除用户", tags = "删除")
@DeleteMapping("{id}")
public void delete(@PathVariable("id") Long id) {
userService.delete(id);
}
其他情况异常
同样的,如果在实体类中,Integer类型的属性加@ApiModelProperty时,必须要给example参数赋值,且值必须为数字对应的字符串。否则也会出现相似异常。
如下示例中的ID字段:
代码语言:javascript复制@Data
@ApiModel(value = "用户实体类",description = "用户信息,用户接受、返回参数")
public class User {
@ApiModelProperty(value = "用户ID", name = "id", example = "0")
private Long id;
@ApiModelProperty(value = "用户名",name = "username",example = "Tom")
private String username;
}