⒈添加pom依赖

         <!-- Swagger核心包,用于扫描程序生成文档数据 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency> <!-- Swagger-ui,用于最终生成可视化UI的 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>

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

 package cn.coreqi.security;

 import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication
@EnableSwagger2
public class HelloWorldApplication { public static void main(String[] args) {
SpringApplication.run(HelloWorldApplication.class, args);
} }

⒊对系统的资源进行说明

  1.控制器  

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

  2.实体类  

 public class User {
private Long id;
@ApiModelProperty(value = "用户名")
private String username;
@ApiModelProperty(value = "密码")
private String password;
private Integer enabled;
}

  3.Action方法 

     @PostMapping("/user")
@ApiOperation(value = "添加用户")
public User create(@Valid @RequestBody User user, BindingResult result){
if(result.hasErrors()){
result.getAllErrors().stream().forEach(error -> {
FieldError fieldError = (FieldError)error;
String message = fieldError.getField() + error.getDefaultMessage();
System.out.println(message);
});
return null;
}
System.out.println(user.toString());
user.setId(5l);
return user;
}

  4.Action方法参数

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

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

05-11 10:56