后端开发中经常需要对移动客户端提供RESTful API接口,在后期版本快速迭代的过程中,修改接口实现的时候都必须同步修改接口文档,而文档与代码又处于两个不同的媒介,除非有严格的管理机制,不然很容易导致写出的代码与接口文档不一致现象。
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。
1.在pom.xml中加入swagger2依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
2.创建swagger2配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.offcn.controller"))
.paths(PathSelectors.any())
.build();
} private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("描述描述")
.termsOfServiceUrl("http://www.baidu.com/")
.contact("Sunny")
.version("1.0")
.build();
}
}
3.Controller增加文档注释
通过@ApiImplicitParams@ApiImplicitParam注解来给参数增加说明
@RestController
@EnableConfigurationProperties({User.class})
@RequestMapping("/user")
public class UserController { @Autowired
User user; private List<User> listUser= Collections.synchronizedList(new ArrayList<User>()); //查询所有
@GetMapping("/")
@ApiOperation(value="查询All用户信息", notes="All用户信息")
public List<User> getAllUser(){
return listUser;
}
//获取指定id的user
@GetMapping("/{id}")
@ApiOperation(value="查询指定id用户信息", notes="根据id查用户信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
public User getUser(@PathVariable("id") Long id){
for(User u:listUser){
if(u.getId()==id){
return user;
}
}
return null;
}
//插入
@PostMapping("/")
@ApiOperation(value="插入用户", notes="插入用户信息")
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
public String insert(User user){
listUser.add(user);
return "success";
}
//根据id修改
@PutMapping("/{id}")
@ApiOperation(value="更新指定id用户信息", notes="根据id更新用户信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
})
public String update(@PathVariable("id") Long id,User user){
for (User user2 : listUser) {
if(user2.getId()==id) {
user2.setName(user.getName());
user2.setAge(user.getAge());
}
}
return "success";
}
//根据id删除
@DeleteMapping("/{id}")
@ApiOperation(value="删除指定id用户信息", notes="根据id删除用户信息")
@ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Long")
public String delete(@PathVariable("id") Long id){
listUser.remove(getUser(id));
return "success";
} }
4.启动tomcat:
访问地址:http://localhost:8080/swagger-ui.html
即可看到上面的API