之前在学习中一直使用postman今天学习了Knife4j,查看接口信息和测试接口更加的便捷了
1,首先需要添加依赖:
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>${knife4j}</version>
</dependency>
2,下面是官方文档中的例子
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
Docket docket=new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder()
//.title("swagger-bootstrap-ui-demo RESTful APIs")
.description("# swagger-bootstrap-ui-demo RESTful APIs")
.termsOfServiceUrl("http://www.xx.com/")
.contact("xx@qq.com")
.version("1.0")
.build())
//分组名称
.groupName("2.X版本")
.select()
//这里指定Controller扫描包路径
.apis(RequestHandlerSelectors.basePackage("com.github.xiaoymin.knife4j.controller"))
.paths(PathSelectors.any())
.build();
return docket;
}
}
3,配置静态资源映射
<mvc:resources location="classpath:/META-INF/resources/" mapping="doc.html"/>
<mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>
最后启动后就可以通过访问localhost:端口号/doc.html
之前有想过可不可以把doc.html 结果是我想多了。。。
Swagger常用注解
1,@Api 用在类上面,例如
@Api(tags = "员工相关接口")
tags不可以省略,省略后虽然不报错,但是在接口文档中不会显示
2,@ApiOperation 用在方法上面,例如
@ApiOperation(value = "员工登录")
value可以省略,直接写成
@ApiOperation("员工登录")
3,@ApiModel,用在实体类上,描述实体类信息
@ApiModel(description = "员工登录时传递的数据模型")
description不可以胜率
4,@ApiModelProperty ,用在属性上面,描述属性信息,例如
@ApiModelProperty("用户名")
总结:利用Knife4j可以快速查看接口文档并且测试接口,常用在开发阶段,设计阶段仍然需要Yapi
Swagger的四个注解简而言之都是写注释用的,用于在接口文档中显示,增强文档的可读性。