Swagger作为一款API文档生成工具,虽然功能已经很完善了,但是还是有些不足的地方。偶然发现knife4j弥补了这些不足,赋予了Swagger更多的功能,今天我们来讲下它的使用方法。
knife4j是springfox-swagger的增强UI实现,为Java开发者在使用Swagger的时候,提供了简洁、强大的接口文档体验。knife4j完全遵循了springfox-swagger中的使用方式,并在此基础上做了增强功能,如果你用过Swagger,你就可以无缝切换到knife4j。
接下来我们来介绍下如何在SpringBoot中使用knife4j,仅需两步即可!
<!--整合Knife4j-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.4</version>
</dependency>
/**
* Swagger2API文档的配置
*/
@Configuration
@EnableSwagger2
@EnableKnife4j
public class Swagger2Config {
}
接下来我们对比下Swagger,看看使用knife4j和它有啥不同之处!
平时一直使用Swagger,但是Swagger的JSON支持一直不是很好,JSON不能折叠,太长没法看,传JSON格式参数时,没有参数校验功能。这些痛点,在knife4j上都得到了解决。
knife4j也支持在头部添加Token,用于登录认证使用。
Authorize
功能中添加登录返回的Token;knife4j支持导出离线文档,方便发送给别人,支持Markdown格式。
文档管理->离线文档
功能,然后选择下载Markdown
即可;knife4j支持临时设置全局参数,支持两种类型query(表单)、header(请求头)。
appType
这个请求头了。有时候我们创建和修改的接口会使用同一个对象作为请求参数,但是我们创建的时候并不需要id,而修改的时候会需要id,此时我们可以忽略id这个属性。
@ApiOperationSupport
注解来忽略这些属性;/**
* 品牌管理Controller
* Created by macro on 2019/4/19.
*/
@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;
}
}
官方文档:https://doc.xiaominfo.com/guide/
https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-knife4j