使用Swagger自动生成API文档

⒈添加pom依赖

 1         <!-- Swagger核心包,用于扫描程序生成文档数据 -->
 2         <dependency>
 3             <groupId>io.springfox</groupId>
 4             <artifactId>springfox-swagger2</artifactId>
 5             <version>2.9.2</version>
 6         </dependency>
 7 
 8         <!-- Swagger-ui,用于最终生成可视化UI的 -->
 9         <dependency>
10             <groupId>io.springfox</groupId>
11             <artifactId>springfox-swagger-ui</artifactId>
12             <version>2.9.2</version>
13         </dependency>

⒉在主程序启动类上添加@EnableSwagger2注解

 1 package cn.coreqi.security;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 import springfox.documentation.swagger2.annotations.EnableSwagger2;
 6 
 7 @SpringBootApplication
 8 @EnableSwagger2
 9 public class HelloWorldApplication {
10 
11     public static void main(String[] args) {
12         SpringApplication.run(HelloWorldApplication.class, args);
13     }
14 
15 }

⒊对系统的资源进行说明

  1.控制器  

1 @RestController
2 @Api(value="操作用户控制器",tags={"操作用户控制器"})
3 public class UserController {
4     ...
5 }

  2.实体类  

1 public class User {
2     private Long id;
3     @ApiModelProperty(value = "用户名")
4     private String username;
5     @ApiModelProperty(value = "密码")
6     private String password;
7     private Integer enabled;
8 }

  3.Action方法 

 1     @PostMapping("/user")
 2     @ApiOperation(value = "添加用户")
 3     public User create(@Valid @RequestBody User user, BindingResult result){
 4         if(result.hasErrors()){
 5             result.getAllErrors().stream().forEach(error -> {
 6                 FieldError fieldError = (FieldError)error;
 7                 String message = fieldError.getField() + error.getDefaultMessage();
 8                 System.out.println(message);
 9             });
10             return null;
11         }
12         System.out.println(user.toString());
13         user.setId(5l);
14         return user;
15     }

  4.Action方法参数

1     @DeleteMapping("/user/{id:\\d+}")  //使用正则指定Id为数字
2     public void delete(@ApiParam(value = "需要删除用户的ID") @PathVariable Long id){
3         System.out.println(id);
4     }

 

⒋访问http://localhost:8080/swagger-ui.html

posted @ 2019-03-28 11:14  SpringCore  阅读(977)  评论(0编辑  收藏  举报