前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Boot中使用Swagger2异常:Illegal DefaultValue 0 for parameter type integer

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

作者头像
程序新视界
发布2020-03-18 17:20:09
3K0
发布2020-03-18 17:20:09
举报
文章被收录于专栏:丑胖侠丑胖侠

在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;
} 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 其他情况异常
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档