简介
前后端分离开发模式中,api文档是最好的沟通方式。
Swagger
是一个规范和完整的框架,用于生成、描述、调用和可视化RESTful
风格的 Web 服务
。
1、及时性 (接口变更后,能够及时准确地通知相关前后端开发人员)
2、规范性 (并且保证接口的规范性,如接口的地址,请求方式,参数及响应格式和错误信息)
3、一致性 (接口信息一致,不会出现因开发人员拿到的文档版本不一致,而出现分歧)
4、可测性 (直接在接口文档上进行测试,以方便理解业务),这个功能我觉得比Postman好用
一、引入Swagger相关依赖
<dependencies>
<!-- Swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<!-- Swagger-ui.html -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
二、创建配置文件
@Configuration
@EnableSwagger2
public class Swagger2Config {
// API接口包扫描的路径
public static final String SWAGGER2_SCAN_PACKAGE = "top.liuchengyin.swagger2";
// API文档的版本
public static final String VERSION = "1.0.0";
@Bean
public Docket creatRestApi(){
return new Docket(DocumentationType.SWAGGER_2) // Swagger2类型的文档
.apiInfo(webApiInfo()) // 设置Api文档信息
.select() // 返回ApiSelectorBuilder控制哪些接口暴露给Swagger展示
// .paths(Predicates.not(PathSelectors.regex("/error.*"))) // 不监控的路径
// .paths(PathSelectors.regex("/.*")) // 对根下所有路径进行监控
.apis(RequestHandlerSelectors.basePackage(SWAGGER2_SCAN_PACKAGE)) // API接口包扫描路径 - 可省略
.paths(PathSelectors.any()) // 所有路径都监控
.build(); // 构建Api文档
}
private ApiInfo webApiInfo(){
return new ApiInfoBuilder()
.title("文档标题 - xxx的API文档") // Api文档的标题
.description("文档描述 - xxx服务接口定义") // Api文档的描述
.version(VERSION) // 文档版本
// 作者、文档的License信息、联系邮箱
.contact(new Contact("LCY","www.liuchengyin.com","[email protected]"))
.build(); // 构建Api文档信息
}
}
三、创建Pojo、Service、Controller层
1、创建Pojo类
@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value="user对象",description="用户对象user")
public class User {
private Long id;
@ApiModelProperty(value="用户名",name="name",example="柳成荫")
private String name;
@ApiModelProperty(value="性别",name="sex",example="男")
private String sex;
@ApiModelProperty(value="年龄",name="age",example="22")
private Integer age;
}
这个pojo类中前三个注解是lombok
自动生成get\set\constructor的,类上的注解@ApiModel
是对这个pojo类进行说明的。字段上的注解@ApiModelProperty
是对字段进行说明,example属性即举例字段。
2、创建Service层
这一层主要就是模拟Service层的操作,没有其他作用。
@Service
public class UserServiceImpl implements UserService {
@Override
public User getUserById(Long id) {
// 模拟从数据库中获取数据
User user = new User();
user.setId(id);
user.setName("lcy");
user.setSex("男");
user.setAge(22);
return user;
}
@Override
public List<User> getAllUser() {
// 模拟从数据库中获取数据
List<User> users = new ArrayList<>();
User user1 = new User(1L,"柳成荫","男",22);
User user2 = new User(2L,"九月清晨","女",18);
users.add(user1);
users.add(user2);
return users;
}
@Override
public User updateUser(User user) {
// 模拟修改数据库中的数据
return user;
}
@Override
public Integer deleteUserById(Long id) {
// 模拟删除数据库中的数据
return 1; // 1表示成功,0表示失败
}
@Override
public User addUser(User user) {
// 模拟数据库新增数据
user.setId(3L);
return user;
}
@Override
public Integer uploadFile(MultipartFile file) {
// 模拟上传文件
return 1; // 1表示成功,0表示失败
}
}
3、创建Controller层
@RestController
@RequestMapping("/lcy")
@Api(description = "用户相关接口")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/getUserById/{id}")
@ApiOperation(value = "获取用户信息",notes = "根据用户Id来获取用户详细信息")
@ApiImplicitParam(name = "id",value = "用户ID",required = true,paramType = "path",dataType = "Long")
public User getUserById(@PathVariable("id") Long id){
return userService.getUserById(id);
}
@GetMapping("/getTest/{id}/{name}")
@ApiOperation(value = "获取用户信息",notes = "根据用户id和name获取详细信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id",value = "用户id",required = true,paramType = "path",dataType = "long"),
@ApiImplicitParam(name = "name",value = "用户name",required = true,paramType = "path",dataType = "String")
})
public User getUser(@PathVariable Long id,@PathVariable String name){
return new User(id,name,"男",22);
}
@ApiOperation(value = "修改用户信息",notes = "根据用户id去修改用户信息")
@ApiImplicitParam(name = "user",value = "用户信息",required = true,dataType = "User")
@PutMapping("/updateUser")
public User updateUser(@RequestBody User user){
return userService.updateUser(user);
}
@GetMapping("/getAllUser")
public List<User> getAllUser(){
return userService.getAllUser();
}
@DeleteMapping("/deleteUerById/{id}")
public Integer deleteUserById(@PathVariable Long id){
return userService.deleteUserById(id);
}
@PostMapping("/addUser")
public User addUser(@RequestBody User user){
return userService.addUser(user);
}
@PostMapping("/uploadFile")
public Integer uploadFile(MultipartFile file){
return userService.uploadFile(file);
}
}
该类主要注重@ApiOperation
和@ApiImplicitParam
注解。@ApiOperation
注解主要是对这个接口方法进行说明,@ApiImplicitParam
注解主要是对参数进行说明。
四、启动项目
启动SpringBoot
项目,我们通过默认进入swagger页面的方式进入到文档页面localhost:8080/swagger-ui.html
点击user-controller
展开接口方法。
点开查看详情,注意因为是通过路径获取参数的(@PathVariable
),因此需要在@ApiImplicitParam
注解里需要添加属性paramType = "path"
,否则会出现String无法转换为其他类型的错误。
在id
输入框输入id,点击下方的try it out
,即可获取到结果。
上面的截图是对常用注解和文档中对应的信息进行解释,且上面的例子是基本类型的参数,如果参数是对象、上传的文件,又是怎么一回事呢?
1、参数为对象时
当参数是一个User对象,且请求为PUT请求时。
结果:
当参数是一个User对象,且请求为POST请求时。
2、参数为文件时
可以直接选择文件,是不是很方便。
五、Swagger常见注解
1、标记Pojo的注解
@ApiModel
标记类、@ApiModelProperty
标记属性字段。
更多信息请见:Swagger注解-@ApiModel 和 @ApiModelProperty、百度
2、标记Controller的注解
①@ApiOperation
用在方法上,说明方法的作用,每一个url资源的定义,使用方式。
②@ApiImplicitParams
、@ApiImplicitParam
对于方法参数的说明,@ApiImplicitParams
里可以包含多个@ApiImplicitParam
,每一个@ApiImplicitParam
都是一个参数说明。
③@ApiIgnore()
用在方法上,表示忽略该方法,不加入文档。
④@Api
用在Controller类上,说明该类的作用。可以标记一个Controller类做为swagger 文档资源。
更多信息请见:Swagger 常用注解使用详解、百度