Swagger 2是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。简单来说,根据项目的接口生成规范化的接口文档,而且可以进行接口的测试类似于post man。话不多说,开始今天的学习。
(1)创建spring项目,引入web依赖,手动添加swagger的相关依赖。
pom.xml如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--swagger可视化依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
(2)创建swagger配置类,提供一个Docket的Bean。
@Configuration
//Swagger2开启注解
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
//引入controller文件夹路径
.apis(RequestHandlerSelectors.basePackage("com.example.swagger.controller"))
//接口生成包含所有的路径
.paths(PathSelectors.any())
.build().apiInfo(new ApiInfoBuilder()
//设置文档的相关信息
.description("接口文档的描述信息")
.title("项目接口文档")
.contact(new Contact("boy","http://www.baidu.com","00@gmail.com"))
.version("v1.0")
.license("Apache2.0")
.build());
}
}
(3)创建实体类user
@ApiModel
public class User {
//描述model的参数信息
@ApiModelProperty(value = "用户id")
private Integer id;
@ApiModelProperty(value = "用户名")
private String username;
@ApiModelProperty(value = "用户地址")
private String address;
(4)创建user的增删改查的接口,
@RestController
//描述UserController
@Api(tags = "用户管理相关接口")
public class UserController {
//描述getUserById
@ApiOperation(value = "查询用户", notes = "根据用户id查询用户")
//描述getUserById的参数信息
@ApiImplicitParam(name = "id", value = "用户id", required = true, defaultValue = "99")
@GetMapping("/user")
public User getUserById(Integer id) {
User user = new User();
user.setId(id);
return user;
}
@ApiOperation(value = "删除用户", notes = "根据用户id删除用户")
@ApiImplicitParam(name = "id", value = "用户id", required = true, defaultValue = "99")
//自定义返回值信息
@ApiResponses({
@ApiResponse(code = 200, message = "删除成功"),
@ApiResponse(code = 500, message = "删除失败")
})
@DeleteMapping("/user/{id}")
public void deleteUserById(@PathVariable Integer id) {
System.out.println("deleteUserById:" + id);
}
@PutMapping("/user")
//方法若存在多个参数的定义方式
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户id", required = true, defaultValue = "99"),
@ApiImplicitParam(name = "username", value = "用户名", required = true, defaultValue = "javaboy")
})
@ApiOperation(value = "更新用户", notes = "根据用户id更新用户名")
//忽略此接口
//@ApiIgnore
public User updateUsernameById(String username, Integer id) {
User user = new User();
user.setId(id);
user.setUsername(username);
return user;
}
@PostMapping("/user")
@ApiOperation(value = "添加用户", notes = "添加用户接口")
public User addUser(@RequestBody User user) {
return user;
}
}
(5)运行项目,访问http://localhost:8080/swagger-ui.html
此时,swagger在线接口文档已经成功生成。