Swagger 2 是一个开源软件框架,可以帮助开发人员设计、构建、记录和使用 RESTful Web 服务,它将代码和文档融为一体,使开发人员将大部分精力集中到业务中,而不是繁杂琐碎的文档中。
创建 Spring Boot Web项目 ,添加 Swagger 2 依赖
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<version>2.9.2version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
<version>2.9.2version>
dependency>
接下来创建 Swagger 2 的配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("org.sang.controller"))
.build().apiInfo(new ApiInfoBuilder()
.description("微人事接口测试文档")
.contact(new Contact("唐三","http://www.baidu.com","tangsan@qq.com"))
.version("v1.0")
.title("API 测试文档")
.license("Apache2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0").build());
}
}
代码解释:
然后开发接口
@RestController
@Api(tags = "用户数据接口")
public class UserController {
@ApiOperation(value = "查询用户", notes = "根据id查询用户")
@ApiImplicitParam(paramType = "path", name = "id", value = "用户id", required = true)
@GetMapping("/user/{id}")
public String getUserById(@PathVariable Integer id) {
return "/user/" + id;
}
@ApiResponses({
@ApiResponse(code = 200,message = "删除成功"),
@ApiResponse(code = 200,message = "删除失败")
})
@ApiOperation(value = "删除用户",notes = "通过id删除用户")
@DeleteMapping("/user/{id}")
public Integer deleteUserById(@PathVariable Integer id) {
return id;
}
@ApiOperation(value = "添加用户",notes = "添加一个用户,传入用户名和地址")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query",name = "username",value = "用户名",required = true,defaultValue = "tangsan"),
@ApiImplicitParam(paramType = "query",name = "address",value = "用户地址",required = true,defaultValue = "ribensheng"),
})
@PostMapping("/user")
public String addUser(@RequestParam String username,@RequestParam String address){
return username+":"+address;
}
@ApiOperation(value = "修改用户",notes = "修改用户,传入用户信息")
@PutMapping("/user")
public String updateUser(@RequestBody User user){
return user.toString();
}
@GetMapping("/ignore")
@ApiIgnore
public void ingoreMethod(){
}
}
代码解释:
相关实体类 User
@ApiModel(value = "用户实体类",description = "用户信息描述类")
public class User {
@ApiModelProperty(value = "用户名")
private String username;
@ApiModelProperty(value = "用户地址")
private String address;
@Override
public String toString(){
return "username:"+username+",address:"+address;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
最后启动 Spring Boot 项目,“http://localhost:8080/swagger-ui.html”,查看接口文档
展开用户数据接口,即可看到所有接口的描述
点击添加用户,查看接口详情