后端开发中经常需要对移动客户端提供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注解来给参数增加说明
1 @RestController
2 @EnableConfigurationProperties({User.class})
3 @RequestMapping("/user")
4 public class UserController {
5
6 @Autowired
7 User user;
8
9 private List<User> listUser= Collections.synchronizedList(new ArrayList<User>());
10
11 //查询所有
12 @GetMapping("/")
13 @ApiOperation(value="查询All用户信息", notes="All用户信息")
14 public List<User> getAllUser(){
15 return listUser;
16 }
17 //获取指定id的user
18 @GetMapping("/{id}")
19 @ApiOperation(value="查询指定id用户信息", notes="根据id查用户信息")
20 @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
21 public User getUser(@PathVariable("id") Long id){
22 for(User u:listUser){
23 if(u.getId()==id){
24 return user;
25 }
26 }
27 return null;
28 }
29 //插入
30 @PostMapping("/")
31 @ApiOperation(value="插入用户", notes="插入用户信息")
32 @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
33 public String insert(User user){
34 listUser.add(user);
35 return "success";
36 }
37 //根据id修改
38 @PutMapping("/{id}")
39 @ApiOperation(value="更新指定id用户信息", notes="根据id更新用户信息")
40 @ApiImplicitParams({
41 @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
42 @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
43 })
44 public String update(@PathVariable("id") Long id,User user){
45 for (User user2 : listUser) {
46 if(user2.getId()==id) {
47 user2.setName(user.getName());
48 user2.setAge(user.getAge());
49 }
50 }
51 return "success";
52 }
53 //根据id删除
54 @DeleteMapping("/{id}")
55 @ApiOperation(value="删除指定id用户信息", notes="根据id删除用户信息")
56 @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Long")
57 public String delete(@PathVariable("id") Long id){
58 listUser.remove(getUser(id));
59 return "success";
60 }
61
62 }
4.启动tomcat:
访问地址:http://localhost:8080/swagger-ui.html
即可看到上面的API