SpringBoot整合Swagger2
添加依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
添加Swagger配置类
接下来在 config
包下创建一个 Swagger 配置类 Swagger2Configuration
,在配置类上加入注解 @EnableSwagger2
,表明开启 Swagger,注入一个 Docket 类来配置一些 API 相关信息,apiInfo()
方法内定义了几个文档信息,代码如下:
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
编写API文档
在 domain
包下创建一个 User
实体类,使用 @ApiModel
注解表明这是一个 Swagger 返回的实体,@ApiModelProperty
注解表明几个实体的属性,代码如下(其中 getter/setter 省略不显示):
@ApiModel(value = "用户", description = "用户实体类")
public class User {
@ApiModelProperty(value = "用户 id", hidden = true)
private Long id;
@ApiModelProperty(value = "用户姓名")
private String name;
@ApiModelProperty(value = "用户年龄")
private String age;
最后,在 controller
包下创建一个 UserController
类,提供用户 API 接口,代码如下:
@RestController
@RequestMapping("/users")
@Api(tags = "用户管理接口")
public class UserController {
Map<Long, User> users = Collections.synchronizedMap(new HashMap<>());
@GetMapping("/")
@ApiOperation(value = "获取用户列表", notes = "获取用户列表")
public List<User> getUserList() {
return new ArrayList<>(users.values());
}
@PostMapping("/")
@ApiOperation(value = "创建用户")
public String addUser(@RequestBody User user) {
users.put(user.getId(), user);
return "success";
}
@GetMapping("/{id}")
@ApiOperation(value = "获取指定 id 的用户")
@ApiImplicitParam(name = "id", value = "用户 id", paramType = "query", dataTypeClass = Long.class, defaultValue = "999", required = true)
public User getUserById(@PathVariable Long id) {
return users.get(id);
}
@PutMapping("/{id}")
@ApiOperation(value = "根据 id 更新用户")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户 id", defaultValue = "1"),
@ApiImplicitParam(name = "name", value = "用户姓名", defaultValue = "wupx"),
@ApiImplicitParam(name = "age", value = "用户年龄", defaultValue = "18")
})
public User updateUserById(@PathVariable Long id, @RequestParam String name, @RequestParam Integer age) {
User user = users.get(id);
user.setName(name);
user.setAge(age);
return user;
}
@DeleteMapping("/{id}")
@ApiOperation(value = "删除用户", notes = "根据 id 删除用户")
@ApiImplicitParam(name = "id", value = "用户 id", dataTypeClass = Long.class, required = true)
public String deleteUserById(@PathVariable Long id) {
users.remove(id);