学习使用swagger2自动生成api文档
什么是swagger2
随着前后端分离的使用,进行接口的说明文档变的很有必要了,Swagger2 是一个自动生成api说明文档的框架,它可以动态生成Api接口文档,降低沟通成本,促进项目高效开发。并且与springboot整合方便,
添加pom依赖
<!--swagger2的依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--swagger的ui界面-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
创建配置类
@Configuration //配置类的形式
@EnableSwagger2 //开启swagger2注解
public class Swagger2 {
@Bean
public Docket creatApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("需要扫描注解的包"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("标题")
.description("说明文档")
.termsOfServiceUrl("项目地址")
.contact("sunf")
.version("版本")
.build();
}
}
swagger2在controller中的使用
@Controller
@Api(tags = "学生管理的controller")
/*
@Api:用在请求的类上,表示对类的说明
tags="说明该类的作用,可以在UI界面上看到的注解"
value="该参数没什么意义,在UI界面上也看到,所以不需要配置"
*/
public class StudentController {
@RequestMapping(value = "/get",method = RequestMethod.GET)
@ResponseBody
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "用户姓名",required = true),
@ApiImplicitParam(name = "age", value = "年龄",dataType = "int")
})
/*
* @ApiImplicitParams:描述方法的参数,内容是一个数组,数组中的内容是@ApiImplicitParam
* @ApiImplicitParam:描述接口中获得的参数
* name:参数名
value:参数的汉字说明、解释
required:参数是否必须传
dataType:参数类型,默认String,其它值dataType="Integer"
defaultValue:参数的默认值
* */
@ApiOperation(value = "获取用户的信息",httpMethod = "GET")
/*
* @ApiOperation:用在请求的方法上,说明方法的用途、作用
value="说明方法的用途、作用"
notes="方法的详细备注说明"
httpMethod = "请求的方式,此处必须是大写的。例如GET、POST"
* */
@ApiResponses({
@ApiResponse(code=400,message="请求参数没填好"),
@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
/*
* @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类
* */
public Student get(@RequestParam String name, Integer age) {
Student student = new Student();
student.setName(name);
student.setAge(age);
student.setAddress("宋家庄");
return student;
}
}
swagger2在domain中的使用
@Data
@ApiModel(value = "返回的实体类",description = "用于返回值")
/*
* @ApiModel:用于实体类上,一般用来@RequestBody说明放回值。
* */
public class Student {
@ApiModelProperty(name = "学生姓名",example = "周星驰",dataType = "string")
/*
* @ApiModelProperty:实体类属性的描述。
* */
private String name;
@ApiModelProperty(value = "学生年龄",notes = "notes")
private Integer age;
@ApiModelProperty(allowEmptyValue = true)
private String address;
}
查看api文档
项目运行起来后访问:http://127.0.0.1:8080/项目根路径/swagger-ui.html, 由于ui界面是swagger提供的,所以访问的页面是固定的。
总结
注解的使用总结: