关于knife4j的使用及配置
作者:_不负时光
knife4j的使用配置
关键词:swagger、springfox、swagger-bootstrap-ui
说明:一款更加美化,实用、方便生成漂亮离线文档的接口文档工具
第一步
引入依赖
<dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>2.0.8</version> <type>pom</type> </dependency>
第二步
配置swagger
@EnableSwagger2
@Component
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("default")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("xxx.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("xxx接口说明")
.description("OpenAPI规范接口描述")
.version("v1.0")
.contact(new Contact("xxx公司", "http://xxx.com/", "xxx@xxx.com"))
.license("License")
.licenseUrl("http://xxx.com/")
.build();
}
}第三步
控制器加swagger-ui 注解(略)
第四步
启动访问
启动springboot 项目
访问:localhost:port/doc.html
knife4j 简单使用
Swagger作为一款API文档生成工具,虽然功能已经很完善了,但是还是有些不足的地方。
knife4j简介
knife4j完全遵循了springfox-swagger中的使用方式,并在此基础上做了增强功能,如果用过Swagger,可以无缝切换到knife4j。
快速开始
1、 在pom.xml中增加knife4j的相关依赖
<!--整合Knife4j--> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>2.0.4</version> </dependency>
2、 在Swagger2Config中增加一个@EnableKnife4j注解,该注解可以开启knife4j的增强功能
/**
* Swagger2API文档的配置
*/
@Configuration
@EnableSwagger2
@EnableKnife4j
public class Swagger2Config {
}3、运行我们的SpringBoot应用,访问API文档地址即可查看:
http://localhost:8080/doc.html
功能特点
对比下Swagger,看看使用knife4j和它有啥不同之处
1、 返回结果集支持折叠,方便查看
2、 请求参数有JSON校验功能
3、 knife4j支持导出离线文档,方便发送给别人,支持Markdown格式
直接选择文档管理->离线文档功能,然后选择下载Markdown即可
4、忽略参数属性
有时候我们创建和修改的接口会使用同一个对象作为请求参数,但是我们创建的时候并不需要id,而修改的时候会需要id,此时我们可以忽略id这个属性。
比如这里的创建商品接口,id、商品数量、商品评论数量都可以让后台接口生成无需传递,可以使用knife4j提供的@ApiOperationSupport注解来忽略这些属性
@Api(tags = "PmsBrandController", description = "商品品牌管理")
@Controller
@RequestMapping("/brand")
public class PmsBrandController {
@Autowired
private PmsBrandService brandService;
private static final Logger LOGGER = LoggerFactory.getLogger(PmsBrandController.class);
@ApiOperation("添加品牌")
@ApiOperationSupport(ignoreParameters = {"id","productCount","productCommentCount"})
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public CommonResult createBrand(@RequestBody PmsBrand pmsBrand) {
CommonResult commonResult;
int count = brandService.createBrand(pmsBrand);
if (count == 1) {
commonResult = CommonResult.success(pmsBrand);
LOGGER.debug("createBrand success:{}", pmsBrand);
} else {
commonResult = CommonResult.failed("操作失败");
LOGGER.debug("createBrand failed:{}", pmsBrand);
}
return commonResult;
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
