Swagger学习
-
简介
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务.
官网:swagger官网
-
Swagger使用
1.导入jar包:swagger2、ui /导入依赖
<dependencies> <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>3.0.0</version> </dependency> <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>3.0.0</version> </dependency> </dependencies>
2.开启swagger
@Configuration @EnableSwagger2 //开启swagger2 public class SwaggerConfig { }
swagger version2直接访问swagger-ui
http://localhost:8080/swagger-ui.htmlswagger version3.0需要添加并访问swagger-ui
http://localhost:8080/swagger-ui/index.html<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
3.配置swagger信息
//配置swagger的bean实例 @Bean public Docket docket(){ return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()); } //apiInfo信息 public ApiInfo apiInfo(){ Contact contact = new Contact("", "", ""); return new ApiInfo("Api Documentation", "Api Documentation", "1.0", "urn:tos", contact, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList()); }
4.配置swagger扫描接口
使用Docket的select()方法链式函数
在Docket的bean中添加select()方法等如下:
//配置swagger的bean实例 @Bean public Docket docket(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() // RequestHandlerSelectors:配置要扫描的方式 // 1.basePackage():扫描指定包 // 2.any():扫描全部 // 3.none():不扫描 // 4.withMethodAnnotation():扫描方法上的注解 // 5.withClassAnnotation():扫描类上的注解 .apis(RequestHandlerSelectors.basePackage("com.li.swaggerstudy.controller")). //过滤路径--正则表达式 .paths(PathSelectors.ant("")) .build(); }
//获取项目环境 Profiles profiles = Profiles.of("dev"); boolean flag = environment.acceptsProfiles(profiles);
5.swagger配置分组,多个分组使用多个Docket
.groupName("li")
6.swagger扫描实体类
- 使用@ApiModel(“实体类名”)
- RestController方法返回实体类
- 使用@Api 等价于@ApiModel
- @ApiOperation 方法注释
-
总结
- 能给比较难理解的属性和接口,增加注释信息。
- 接口文档实时更新
- 可以在线测试
在发布时候关闭swagger文档,以减少运行内存与保证安全。