0%

Swagger-ui

前言

简单介绍Swagger-ui2.7.0的基本使用

依赖

1
2
3
4
5
6
7
8
9
10
11
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>

注意:不同版本的swagger注解配置有点不一样

使用

  • 先要在Java里面配置Config,并加上@EnableSwagger2Configuration已保证应用启动时可以扫描到配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Configuration
@EnableSwagger2
public class SwaggerConfig {

private ApiInfo webApiInfo() {
return new ApiInfoBuilder()
.title("测试")
.description("接口定义")
.version("1.0")
.contact(new Contact("memo", "http://www.memo.com", "11@qq.com"))
.build();
}

@Bean
public Docket webApiConfig() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("cetc")
.apiInfo(webApiInfo())
.select()
.paths(Predicates.not(PathSelectors.regex("/admin/*")))
.paths(Predicates.not(PathSelectors.regex("/error/*")))
.build();
}
}
  • 类上或者方法上加注解(@Api@ApiOperation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
@Api(tags = {"学生管理"})
@RestController
@RequestMapping("/student")
public class StudentController {

@Autowired
StudentService studentService;

@ApiOperation("查看学生列表")
@GetMapping("/list")
public R getStudentList() {
List<Student> students = studentService.list();
if (students != null && students.size() != 0) {
return R.ok().data("students", students);
}else return R.error();
}
}


// 属性也可以写
@Data
public class R {

@ApiModelProperty(value = "是否成功")
private Boolean success;

@ApiModelProperty(value = "返回状态码")
private Integer code;

@ApiModelProperty(value = "返回消息")
private String message;

@ApiModelProperty(value = "返回数据")
private Map<String, Object> data = new HashMap<>();


private R(){}

public static R ok(){
R r = new R();
r.setSuccess(true);
r.setCode(ResultCode.SUCCESS);
r.setMessage("成功");
return r;
}

public static R error(){
R r = new R();
r.setSuccess(false);
r.setCode(ResultCode.ERROR);
r.setMessage("失败");
return r;
}

public R success(Boolean success){
this.setSuccess(success);
return this;
}

public R code(Integer code){
this.setCode(code);
return this;
}

public R message(String message){
this.setMessage(message);
return this;
}

public R data(String key, Object value){
this.data.put(key, value);
return this;
}

public R data(Map<String, Object> map){
this.setData(map);
return this;
}
}
  • 输入网址:localhost:xxxx/swagger-ui.html