Swagger2教程
作用:编写和维护接口文档。
一、Swagger2 + SpringBoot集成
1.依赖
<!--依赖管理 --> <dependencies> <dependency> <!--添加Web依赖 --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency><!--添加Swagger依赖 --> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency><!--添加Swagger-UI依赖 --> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency> <dependency> <!--添加热部署依赖 --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <dependency><!--添加Test依赖 --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
2.配置类
@Configuration @EnableSwagger2 public class Swagger2Config { @Bean public Docket controllerApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(new ApiInfoBuilder() .title("公路施工管理系统接口文档:") .description("用于道路施工管理") .contact(new Contact("a man who ",null, null)) .version("Version: 1.0.0") .build()) .select() .apis(RequestHandlerSelectors.basePackage("com.demon.swagger2")) .paths(PathSelectors.any()) .build(); } }
3.编写接口文档
Swagger2 基本使用:
-
@Api 描述类/接口的主要用途
-
@ApiOperation 描述方法用途
-
@ApiImplicitParam 描述方法的参数
-
@ApiImplicitParams 描述方法的参数(Multi-Params)
-
@ApiIgnore 忽略某类/方法/参数的文档
使用注解编写文档:
@Api("用户信息管理") @RestController @RequestMapping("/user/*") public class UserController { private final static List<User> userList = new ArrayList<>(); { userList.add(new User(1, "Tom", "A fool cat")); userList.add(new User(2, "Jerry", "A clever mouse")); } @ApiOperation("获取用户列表") @GetMapping("list") public List userList() { return userList; } @ApiOperation("新增用户") @PostMapping("add") public boolean add(User user) { return userList.add(user); } @ApiOperation("更新用户") @ApiImplicitParam(name = "user", value = "单个用户信息", dataType = "User") @PutMapping("update") public boolean update(User user) { return userList.remove(user) && userList.add(user); } @ApiOperation("批量删除用户") @ApiImplicitParam(name = "users", value = "N个用户信息", dataType = "List<User>") @DeleteMapping("delete") public boolean delete(@RequestBody List<User> users) { return userList.removeAll(users); } }
使用:http://localhost:9393/swagger-ui.html