Spring Boot中使用Swagger2异常:Illegal DefaultValue 0 for parameter type integer

在Spring Boot中集成Swagger2,使用@ApiImplicitParam注解时出现如下异常“Illegal DefaultValue 0 for parameter type integer”,异常详情如下:

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]

相关源代码的写法如下:

/**
 * 删除用户
 */
@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"的属性。异常成功解决。正确代码如下:

/**
 * 删除用户
 */
@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字段:

@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;
}

精品SpringBoot 2.x视频教程

《Spring Boot 2.x 视频教程全家桶》精品Spring Boot 2.x视频教程,打造一套最全的Spring Boot 2.x视频教程。


程序新视界

公众号“程序新视界”,一个让你软实力、硬技术同步提升的平台

csdn-微信公众号

发布了546 篇原创文章 · 获赞 5119 · 访问量 336万+

猜你喜欢

转载自blog.csdn.net/wo541075754/article/details/104477848