1.什么是swagger?
前言: Swagger 是一个主要用来在线生成文档的插件,这里主要用来动态生成api接口供前后端进行交互,如果不生成的话就需要写静态文档来交互,那样不仅很慢而且不容易修改,那Swagger就可以解决这个问题。
- 号称世界上最流行的API框架
- Restful Api 文档在线自动生成器 => API 文档 与API 定义同步更新
- 直接运行,在线测试API
- 支持多种语言 (如:Java,PHP等)
2.怎么把swagger集成到项目中来,这里用springboot集成为例
<!--swagger 依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
@Configuration
@EnableSwagger2//开启swagger2
public class SwaggerConfig {
}
这里如果什么都不配置的话,也可以打开swagger.html页面,只不过会是原始页面
@RestController
@Api(tags= "商品控制类",value = "这是对该类一个简单描述")
@RequestMapping("/goods")
public class GoodsController {
@ApiOperation("返回问好")
@GetMapping("/hello")
public String hello(){
return "hello";
}
//只要我们的接口返回值中存在实体类就会扫描到
@ApiOperation("返回一个商品")
@PostMapping("/getGoods")
public Goods hello1(){
return new Goods();
}
//只要我们的接口返回值中存在实体类就会扫描到
@ApiOperation("返回传入的姓名")
@GetMapping("/helloGoods")
public String hello2(String name){
return "hello" + name;
}
}
2.3 编写实体类
@ApiModel("商品实体类")
public class Goods {
@ApiModelProperty("商品ID")
private Integer id;
@ApiModelProperty("商品名字")
private String name;
@ApiModelProperty("商品价格")
private Double price;
@ApiModelProperty("商品数量")
private Integer count;
}
//此处省略set/get 方法....
用到的一些注解:
- @Api()用于类; 表示标识这个类是swagger的资源
- @ApiOperation()用于方法; 表示一个http请求的操作
- @ApiParam()用于方法,参数,字段说明;
表示对参数的添加元数据(说明或是否必填等) - @ApiModel()用于类
表示对类进行说明,用于参数用实体类接收 - @ApiModelProperty()用于方法,字段
表示对model属性的说明或者数据操作更改 - @ApiIgnore()用于类,方法,方法参数
表示这个方法或者类被忽略 - @ApiImplicitParam() 用于方法
表示单独的请求参数 - @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam
2.4 最终效果图
2.5 其他配置功能
- 配置作者信息
//配置swagger信息 apiInfo public ApiInfo apiInfo(){ //作者信息 Contact contact = new Contact("血手人屠","","1723246792@qq.com"); return new ApiInfo("swaggerApi文档", "这个作者有点酷", "1.0", "urn:tos", contact, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList()); }
- 效果
- 配置分组信息,我这里是通过包来进行分组
/** * 设置基础分组 里面包含所有注解标注过的接口 * @return */ @Bean public Docket docket(){ return new Docket(DocumentationType.SWAGGER_2). apiInfo(apiInfo()) .select() //requestHandlerSelectors 配置要扫描接口的方式 .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller")) .build() .groupName("所有路径分组"); } /** * * 设置demo2分组 - 匹配指定请求路径 * @return */ @Bean public Docket docket2(){ return new Docket(DocumentationType.SWAGGER_2). apiInfo(apiInfo()) .select() //requestHandlerSelectors 配置要扫描接口的方式 .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller.test")) .build() .groupName("第二种分组"); }
- 效果
- 效果
-
2.5 其他一些页面上的版块
- 2.5.1 这里的一些访问请求方式是根据controller层中请求方式决定的
如果访问方式是@RequestMapping 那这里就会像Test控制层中的方法一样,将所有方式都展现出来
- 2.5.1 这里的一些访问请求方式是根据controller层中请求方式决定的
- 2.5.2 只要controller中接口的返回值有该类,就会扫描到这个实体类显示model版块