一. 概述
参考开源项目https://github.com/xkcoding/spring-boot-demo
现在基本都是前后端分离了,后端写好接口一般都需要提供接口文档给前端,如果一个个手写就会费工又费时. 本DEMO将介绍SpringBoot整合Swagger自动生成接口文档,还可以在线调试接口
二. SpringBootDemo
2.1 引入依赖
<properties>
<battcn.swagger.version>2.1.5-RELEASE</battcn.swagger.version>
<swagger-ui-layer>1.1.3</swagger-ui-layer>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.battcn</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>${battcn.swagger.version}</version>
<!-- 不喜欢这个ui,可以屏蔽然后引入日期UI -->
<!-- <exclusions>-->
<!-- <exclusion>-->
<!-- <groupId>com.battcn</groupId>-->
<!-- <artifactId>swagger-vue-ui</artifactId>-->
<!-- </exclusion>-->
<!-- </exclusions>-->
</dependency>
<!-- 其他swagger ui-->
<!-- <dependency>-->
<!-- <groupId>com.github.xiaoymin</groupId>-->
<!-- <artifactId>swagger-bootstrap-ui</artifactId>-->
<!-- <version>1.9.6</version>-->
<!-- </dependency>-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
2.2 application.yml
server:
port: 8080
servlet:
context-path: /demo
spring:
swagger:
# 是否启用swagger
enabled: true
# 接口信息
title: spring-boot-demo
description: 这是一个简单的 Swagger API 演示
version: 1.0.0-SNAPSHOT
contact:
name: wangpr
email: 123456@qq.com
# swagger扫描的基础包,默认:全扫描
# base-package:
# 需要处理的基础URL规则,默认:/**
base-path:
- /user/**
- /goods/**
# 需要排除的URL规则,默认:空
# exclude-path:
# 认证
# security:
# # 是否启用 swagger 登录验证
# filter-plugin: true
# username: admin
# password: 123456
# 全局消息体
global-response-messages:
GET[0]:
code: 400
message: Bad Request,一般为请求参数不对
GET[1]:
code: 404
message: NOT FOUND,一般为请求路径不对
GET[2]:
code: 500
message: ERROR,一般为程序内部错误
POST[0]:
code: 400
message: Bad Request,一般为请求参数不对
POST[1]:
code: 404
message: NOT FOUND,一般为请求路径不对
POST[2]:
code: 500
message: ERROR,一般为程序内部错误
#全局参数,比如Token之类的验证信息可以全局话配置
global-operation-parameters:
# 描述信息
- description: 'Token信息,必填项'
# 指定参数类型
modelRef: 'string'
# 参数名
name: 'Authorization'
# 指定参数存放位置,参考ParamType:(header,query,path,body,form)
parameter-type: 'header'
# 指定参数是否必传,默认false
required: true
# 分组
# groups:
# user-group:
# title: spring-boot-demo
# base-path: /**
2.3 启动类
@SpringBootApplication
public class SpringBootDemoSwaggerBeautyApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoSwaggerBeautyApplication.class, args);
}
}
2.4 统一响应类: ApiResponse.java
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "通用PI接口返回", description = "Common Api Response")
public class ApiResponse<T> implements Serializable {
private static final long serialVersionUID = -8987146499044811408L;
/**
* 通用返回状态
*/
@ApiModelProperty(value = "通用返回状态", required = true)
private Integer code;
/**
* 通用返回信息
*/
@ApiModelProperty(value = "通用返回信息", required = true)
private String message;
/**
* 通用返回数据
*/
@ApiModelProperty(value = "通用返回数据", required = true)
private T data;
}
2.5 实体类: User.java
@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "用户实体", description = "User Entity")
public class User implements Serializable {
private static final long serialVersionUID = 5057954049311281252L;
/**
* 主键id
*/
@ApiModelProperty(value = "主键id", required = true)
private Integer id;
/**
* 用户名
*/
@ApiModelProperty(value = "用户名", required = true)
private String name;
/**
* 工作岗位
*/
@ApiModelProperty(value = "工作岗位", required = true)
private String job;
}
2.6 控制层: UserController.java
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
@Slf4j
public class UserController {
@GetMapping
@ApiOperation(value = "条件查询(DONE)", notes = "备注")
@ApiImplicitParams({@ApiImplicitParam(name = "username", value = "用户名", dataType = DataType.STRING,required = true, defaultValue = "xxx")})
public ApiResponse<User> getByUserName(String username) {
log.info("多个参数用 @ApiImplicitParams");
return ApiResponse.<User>builder().code(200).message("操作成功").data(new User(1, username, "JAVA")).build();
}
@GetMapping("/{id}")
@ApiOperation(value = "主键查询(DONE)", notes = "备注")
@ApiImplicitParams({@ApiImplicitParam(name = "id", value = "用户编号", dataType = DataType.INT, paramType = ParamType.PATH)})
public ApiResponse<User> get(@PathVariable Integer id) {
log.info("单个参数用 @ApiImplicitParam");
return ApiResponse.<User>builder().code(200).message("操作成功").data(new User(id, "u1", "p1")).build();
}
@DeleteMapping("/{id}")
@ApiOperation(value = "删除用户(DONE)", notes = "备注")
@ApiImplicitParam(name = "id", value = "用户编号", dataType = DataType.INT, paramType = ParamType.PATH)
public void delete(@PathVariable Integer id) {
log.info("单个参数用 ApiImplicitParam");
}
@PostMapping
@ApiOperation(value = "添加用户(DONE)")
public User post(@RequestBody User user) {
log.info("如果是 POST PUT 这种带 @RequestBody 的可以不用写 @ApiImplicitParam");
return user;
}
@PostMapping("/multipar")
@ApiOperation(value = "添加用户(DONE)")
public List<User> multipar(@RequestBody List<User> user) {
log.info("如果是 POST PUT 这种带 @RequestBody 的可以不用写 @ApiImplicitParam");
return user;
}
@PostMapping("/array")
@ApiOperation(value = "添加用户(DONE)")
public User[] array(@RequestBody User[] user) {
log.info("如果是 POST PUT 这种带 @RequestBody 的可以不用写 @ApiImplicitParam");
return user;
}
@PutMapping("/{id}")
@ApiOperation(value = "修改用户(DONE)")
public void put(@PathVariable Long id, @RequestBody User user) {
log.info("如果你不想写 @ApiImplicitParam 那么 swagger 也会使用默认的参数名作为描述信息 ");
}
@PostMapping("/{id}/file")
@ApiOperation(value = "文件上传(DONE)")
public String file(@PathVariable Long id, @RequestParam("file") MultipartFile file) {
log.info(file.getContentType());
log.info(file.getName());
log.info(file.getOriginalFilename());
return file.getOriginalFilename();
}
}
2.7 打开: http://localhost:8080/demo/swagger-ui.html

网友评论