使用swagger2代替api文档
Swagger的出现方便了api的测试和前后端联调,充当了api文档的作用,其面向切面,无侵入,和springboot完美融合,使用非常简单。
首先引入springfox的两个依赖:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
使用Springboot的注解,常用做法是采用Class配置Swagger页面,涉及到两个重要对像ApiInfo和Docket,用于开启swagger配置,并生成swagger页面的风格。然后就是swagger的ApiInfo的注解。
@EnableSwagger2 @Configuration @ConditionalOnProperty(name = "swagger.enable", havingValue = "true") public class SwaggerConfig { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() // apis(RequestHandlerSelectors.basePackage("com.huawei.dpe") 配置扫描路径 .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) // 扫描特定注解 .paths(PathSelectors.any()) // 监控和显示 .build(); } public ApiInfo apiInfo(){ return new ApiInfoBuilder() // 添加额外信息 .title("swagger测试的头文件") .description("there is no description") .enable(true) .termsOfServiceUrl("http://localhost:8888") .version("1.0") .build(); } }
如果想关闭Swagger,因为使用了ConditionOnProperty,只需在application.yaml中使用如下代码,即可不加载Swagger配置,也就关闭了Swagger。
swagger: enable:false
如果要详尽的接口描述,还得写接口文档。
在快速开发过程中,更推荐Knife,文档页面比较友好,有目录索引,既可以看注释,又可以调用接口。更重要的是,可以导出markdown文件
参考地址:https://doc.xiaominfo.com/knife4j/
日进有功