在Linux系统中使用Swagger注解,可以帮助开发者更好地生成API文档,提高API的可读性和可维护性。以下是一些常用的Swagger注解及其使用技巧:
@Api: 用于类上,表示这个类是Swagger资源。
@Api(tags = "用户管理")
public class UserController {
// ...
}
@ApiOperation: 用于方法上,描述一个具体的操作。
@ApiOperation(value = "获取用户信息", notes = "根据用户ID获取用户详细信息")
@GetMapping("/users/{id}")
public User getUserById(@PathVariable Long id) {
// ...
}
@ApiParam: 用于方法参数上,提供参数的详细描述。
@ApiOperation(value = "创建用户")
@PostMapping("/users")
public ResponseEntity<User> createUser(@ApiParam(value = "用户对象", required = true) @RequestBody User user) {
// ...
}
@ApiResponse: 用于方法上,描述可能的响应。
@ApiOperation(value = "删除用户")
@DeleteMapping("/users/{id}")
@ApiResponse(code = 204, message = "用户删除成功")
@ApiResponse(code = 404, message = "用户不存在")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
// ...
}
@ApiModel: 用于类上,表示这个类是一个模型。
@ApiModel(description = "用户信息")
public class User {
@ApiModelProperty(value = "用户ID", example = "1")
private Long id;
@ApiModelProperty(value = "用户名", example = "john_doe")
private String username;
// ...
}
@ApiModelProperty: 用于类属性上,提供属性的详细描述。
@ApiModelProperty(value = "用户邮箱", example = "john.doe@example.com")
private String email;
@ApiImplicitParam: 用于方法上,描述非路径或非请求体的参数。
@ApiOperation(value = "搜索用户")
@GetMapping("/users/search")
@ApiImplicitParam(name = "keyword", value = "搜索关键词", required = true, dataType = "string", paramType = "query")
public List<User> searchUsers(@RequestParam String keyword) {
// ...
}
@ApiResponses: 用于方法上,描述多个可能的响应。
@ApiOperation(value = "更新用户")
@PutMapping("/users/{id}")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "用户更新成功"),
@ApiResponse(code = 400, message = "请求参数错误"),
@ApiResponse(code = 404, message = "用户不存在")
})
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
// ...
}
@ApiImplicitParams: 用于方法上,描述多个非路径或非请求体的参数。
@ApiOperation(value = "批量删除用户")
@DeleteMapping("/users/batch")
@ApiImplicitParams({
@ApiImplicitParam(name = "ids", value = "用户ID列表", required = true, dataType = "string", paramType = "query")
})
public ResponseEntity<Void> batchDeleteUsers(@RequestParam List<Long> ids) {
// ...
}
@ApiIgnore: 用于类或方法上,表示忽略该类或方法,不生成文档。
@ApiIgnore
public class InternalService {
// ...
}
在Spring Boot项目中,可以通过配置类来启用Swagger:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
}
example属性提供参数和响应的示例值,帮助用户更好地理解API的使用。tags属性对API进行分组,方便用户按功能模块查找API。@Api注解中使用tags属性来区分不同版本的API。通过合理使用这些Swagger注解,可以显著提高API文档的质量和可维护性。