共计 6183 个字符,预计需要花费 16 分钟才能阅读完成。
SpringBoot2 整合 Swagger2
SpringBoot 整合三板斧
第一步、引入 pom
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.22</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.22</version>
</dependency>
swagger-spring-boot-starter
该我的项目次要利用 Spring Boot 的自动化配置个性来实现疾速的将 swagger2 引入 spring boot 利用来生成 API 文档,简化原生应用 swagger2 的整合代码。
swagger-bootstrap-ui
是 springfox-swagger
的加强 UI 实现,为 Java 开发者在应用 Swagger 的时候,能领有一份简洁、弱小的接口文档体验
swagger-annotations
,swagger-models
是因为 springfox-swagger2
包里有 swagger-models-1.5.20.jar
报错。所以替换成 1.5.22 版本
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:601)
at java.lang.Long.valueOf(Long.java:803)
at io.swagger.models.parameters.AbstractSerializableParameter.getExample(AbstractSerializableParameter.java:412)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at......
看下 1.5.20 版本里 AbstractSerializableParameter.java 源码:
public Object getExample() {if (this.example == null) {return null;} else {
try {if ("integer".equals(this.type)) {return Long.valueOf(this.example);
}
if ("number".equals(this.type)) {return Double.valueOf(this.example);
}
if ("boolean".equals(this.type) && ("true".equalsIgnoreCase(this.example) || "false".equalsIgnoreCase(this.defaultValue))) {return Boolean.valueOf(this.example);
}
} catch (NumberFormatException var2) {LOGGER.warn(String.format("Illegal DefaultValue %s for parameter type %s", this.defaultValue, this.type), var2);
}
return this.example;
}
}
这里只判断了 this.example == null 才返回 null,其余会去进行转换,而空字符串也会进行转换,导致格局抛出格式化转换异样. 再来看下 1.5.22 版本里 AbstractSerializableParameter.java 源码:
public Object getExample() {if (this.example != null && !this.example.isEmpty()) {
try {if ("integer".equals(this.type)) {return Long.valueOf(this.example);
}
if ("number".equals(this.type)) {return Double.valueOf(this.example);
}
if ("boolean".equals(this.type) && ("true".equalsIgnoreCase(this.example) || "false".equalsIgnoreCase(this.defaultValue))) {return Boolean.valueOf(this.example);
}
} catch (NumberFormatException var2) {LOGGER.warn(String.format("Illegal DefaultValue %s for parameter type %s", this.defaultValue, this.type), var2);
}
return this.example;
} else {return this.example;}
}
对 example 同时进行了 null 和空值的判断,官网也发现了本人的这个问题,咱们进行相应的替换即可
第二部、配置
swagger-spring-boot-starter
相干配置信息可参考如下地址:
-
源码地址
- GitHub:https://github.com/dyc87112/s…
- 码云:https://gitee.com/didispace/s…
- 应用样例:https://github.com/dyc87112/s…
- 博客:http://blog.didispace.com
- 社区:http://www.spring4all.com
swagger-bootstrap-ui
相干配置信息可参考如下地址:
官网地址:https://doc.xiaominfo.com/guide/
swagger-bootstrap-ui
目前已改名了knife4j-spring-boot-starter
我的项目正式更名为knife4j, 取名 knife4j 是心愿她能像一把匕首一样玲珑, 轻量, 并且性能强悍, 更名也是心愿把她做成一个为 Swagger 接口文档服务的通用性解决方案, 不仅仅只是专一于前端 Ui 前端.
swagger-bootstrap-ui 的所有个性都会集中在
knife4j-spring-ui
包中, 并且后续也会满足开发者更多的个性化需要.
swagger:
version: 1.0v # 版本号
authorization: # 全局参数
name: Authorization # 鉴权策略 ID,对应 SecurityReferences ID
type: ApiKey # 鉴权策略,可选 ApiKey | BasicAuth | None,默认 ApiKey
key-name: X-Token # 鉴权传递的 Header 参数
# auth-regex: ^.*$ # 须要开启鉴权 URL 的正则, 默认 ^.*$ 匹配所有 URL
ui-config: # 排序规定
operations-sorter: method # 按办法定义程序排序
tags-sorter: alpha # 按字母表排序
docket: # 分组配置
common:
base-package: com.xxxx.a
description: API 接口文档
title: xxx 接口
contact:
name: xxx
url: https://cn.bing.com/
hq:
base-package: com.xxxx.b
description: API 接口文档
title: xxx 接口
contact:
name: xxx
url: https://zc.happyloves.cn:4443/wordpress/
shop:
base-package: com.xxxx.c
description: API 接口文档
title: xxx 接口
contact:
name: xxx
url: https://zc.happyloves.cn
第三步、注解
@EnableSwagger2Doc // 启用 Swagger2
@EnableSwaggerBootstrapUI // 启用 swagger-bootstrap-ui
@SpringBootApplication
public class WebApplication {public static void main(String[] args) {SpringApplication.run(WebApplication.class, args);
}
}
编写代码
@Api(value = "DemoOne-DemoOne 服务~~~~~~~~", tags = {"1-DemoOne-DemoOne 服务"})
@Slf4j
@Validated
@RestController
@RequestMapping("/common/DemoOne")
public class DemoOneController {
private final DemoOneService service;
@Autowired
public DemoOneController(DemoOneService service) {this.service = service;}
//=====================================================================================DELETE=====================================================================================
@ApiOperation(value = "依据主键 ID 删除", notes = "依据主键 ID 删除~~~~~~~~~~~~~")
@DeleteMapping("/{id}")
public ApiMessage deleteById(@PathVariable @Min(1) int id) throws Exception {return service.deleteById(id);
}
//=====================================================================================GET========================================================================================
@ApiOperation(value = "获取所有数据", notes = "获取所有数据~~~~~~~~~~~~~")
@GetMapping("/")
public ApiMessage<List<DemoOneResponse>> getAllList() {return service.getAllList();
}
@ApiOperation(value = "依据主键 ID 获取数据", notes = "依据主键 ID 获取数据~~~~~~~~~~~~~")
@ApiImplicitParams(value = {@ApiImplicitParam(name = "id", required = true, value = "主键 ID", paramType = "path", dataType = "string"),
})
@GetMapping("/{id}/{name}")
public ApiMessage<DemoOneResponse> getById(@PathVariable @Min(1) int id, @PathVariable @AssertFalse boolean name) {return service.getById(id);
}
//=====================================================================================POST=======================================================================================
@ApiOperation(value = "新增 DemoOne 数据", notes = "新增 DemoOne 数据~~~~~~~~~~~~~")
@PostMapping("/")
public ApiMessage<DemoOneResponse> save(@RequestBody @Valid DemoOneRequest parameter) {return service.addDemoOne(parameter);
}
//=====================================================================================PUT========================================================================================
@ApiOperation(value = "更新 DemoOne 数据", notes = "更新 DemoOne 数据~~~~~~~~~~~~~")
@PutMapping("/")
public ApiMessage<DemoOneResponse> update(@RequestBody @Valid DemoOneRequest parameter) {return service.update(parameter);
}
功败垂成!!!启动拜访如下地址:
Swagger2 地址:
http://${ip 地址}:${端口}/swagger-ui.html
swagger-bootstrap-ui 地址:
http://${ip 地址}:${端口}/doc.html
赵小胖集体博客:https://zc.happyloves.cn:4443/wordpress/