在 Spring Boot 项目中,Swagger(主流分为 Swagger 2/Springfox 和 OpenAPI 3/SpringDoc) 是接口文档生成的核心框架,而Knife4j 是基于 Swagger 的增强版(完全兼容 Swagger 注解,同时新增少量专属增强注解)。以下是完整的注解分类及详解,包含 Swagger 2、OpenAPI 3(Swagger 3)、Knife4j 增强注解,附使用场景和示例。
一、核心说明 框架/版本 依赖核心 注解归属包 备注 Swagger 2(Springfox) springfox-swagger2io.swagger.annotations老版本主流,Spring Boot 2.6+ 需适配 OpenAPI 3(Swagger 3) springdoc-openapiio.swagger.v3.oas.annotations新版本标准,兼容 Spring Boot 3.x Knife4j 基于 Swagger 增强 兼容上述所有 +com.github.xiaoymin 美化UI、新增分组/权限等注解
二、Swagger 2(Springfox)核心注解(最常用) 1. 全局/配置类注解 注解 作用 使用位置 @EnableSwagger2启用 Swagger 2 功能 SpringBoot 配置类上 @EnableSwagger2WebMvc非 WebFlux 场景启用 Swagger 2(适配 Spring MVC) 配置类上
2. 接口类注解 注解 作用 示例 @Api标记 Controller 类,描述接口分组信息 @Api(tags = "用户管理接口", description = "用户CRUD操作")@ApiIgnore忽略当前类/方法/参数,不生成到接口文档中 @ApiIgnore @RestController(忽略整个Controller)
3. 接口方法注解 注解 作用 示例 @ApiOperation描述接口方法的功能、备注、响应等 @ApiOperation(value = "根据ID查询用户", notes = "仅返回已激活用户", httpMethod = "GET")@ApiImplicitParams批量描述接口参数(配合@ApiImplicitParam使用) 见下方参数示例 @ApiImplicitParam描述单个请求参数(路径、查询、请求头、表单等) 见下方参数示例 @ApiResponses批量描述接口响应状态码(配合@ApiResponse使用) 见下方响应示例 @ApiResponse描述单个响应状态码、信息、返回模型 见下方响应示例
4. 参数/请求体注解 注解 作用 示例 @ApiImplicitParam单个参数描述(非实体参数) @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "Long", paramType = "path"), @ApiImplicitParam(name = "token", value = "请求令牌", required = true, dataType = "String", paramType = "header")})@ApiParam描述方法参数(直接加在参数前,替代@ApiImplicitParam) public User getUser(@ApiParam(value = "用户ID", required = true) @PathVariable Long userId)@RequestBody标记请求体参数(非Swagger注解,但配合使用) public Result save(@ApiParam(value = "用户信息", required = true) @RequestBody User user)
5. 实体/字段注解 注解 作用 示例 @ApiModel描述实体类(请求体/响应体模型) @ApiModel(value = "UserDTO", description = "用户请求参数模型")@ApiModelProperty描述实体字段的含义、是否必填、示例值、隐藏等 @ApiModelProperty(value = "用户名", required = true, example = "zhangsan", hidden = false) private String username;
Swagger 2 完整示例 // 配置类 @Configuration @EnableSwagger2 public class Swagger2Config { @Bean public Docket createRestApi ( ) { return new Docket ( DocumentationType . SWAGGER_2) . apiInfo ( new ApiInfoBuilder ( ) . title ( "SpringBoot Swagger2 接口文档" ) . description ( "用户管理模块接口" ) . version ( "1.0" ) . build ( ) ) . select ( ) . apis ( RequestHandlerSelectors . basePackage ( "com.example.controller" ) ) // 扫描包 . paths ( PathSelectors . any ( ) ) . build ( ) ; } } // Controller @RestController @RequestMapping ( "/user" ) @Api ( tags= "用户管理接口" , description= "用户CRUD操作" ) public class UserController { @GetMapping ( "/{userId}" ) @ApiOperation ( value= "根据ID查询用户" , notes= "仅返回已激活的用户信息" ) @ApiImplicitParams ( { @ApiImplicitParam ( name= "userId" , value= "用户ID" , required= true , dataType= "Long" , paramType= "path" ) , @ApiImplicitParam ( name= "token" , value= "请求令牌" , required= true , dataType= "String" , paramType= "header" ) } ) @ApiResponses ( { @ApiResponse ( code= 200 , message= "查询成功" , response= UserDTO . class ) , @ApiResponse ( code= 404 , message= "用户不存在" ) , @ApiResponse ( code= 500 , message= "服务器内部错误" ) } ) public Result < UserDTO > getUser ( @PathVariable Long userId, @RequestHeader String token) { // 业务逻辑 return Result . success ( new UserDTO ( ) ) ; } @PostMapping ( "/save" ) @ApiOperation ( value= "新增用户" , notes= "用户名不能为空,密码长度≥6" ) public Result < Void > save ( @ApiParam ( value= "用户信息" , required= true ) @RequestBody UserDTO userDTO) { // 业务逻辑 return Result . success ( ) ; } } // 实体类 @ApiModel ( value= "UserDTO" , description= "用户新增请求参数" ) public class UserDTO { @ApiModelProperty ( value= "用户名" , required= true , example= "zhangsan" , hidden= false ) private String username; @ApiModelProperty ( value= "密码" , required= true , example= "123456" , hidden= true ) // 隐藏密码 private String password; @ApiModelProperty ( value= "年龄" , required= false , example= "20" ) private Integer age; // getter/setter } 三、OpenAPI 3(Swagger 3/SpringDoc)核心注解(新版本推荐) OpenAPI 3 是 Swagger 的标准化版本(OAS 3.0),注解包为io.swagger.v3.oas.annotations,完全替代 Swagger 2,适配 Spring Boot 3.x,Knife4j 也完全兼容。
注解映射(对比 Swagger 2) Swagger 2 注解 OpenAPI 3 注解 作用一致? 补充说明 @Api@Tag是 @Tag(name = "用户接口", description = "...")@ApiOperation@Operation是 @Operation(summary = "查询用户", description = "...")@ApiImplicitParam@Parameter是 加在参数前或@Parameters中 @ApiImplicitParams@Parameters是 批量包裹@Parameter @ApiResponse@ApiResponse是 包路径不同,参数兼容 @ApiResponses@ApiResponses是 同上 @ApiModel@Schema是 加在实体类上,替代@ApiModel @ApiModelProperty@Schema是 加在字段上,替代@ApiModelProperty @ApiParam@Parameter是 加在参数前 @ApiIgnore@Hidden是 忽略类/方法/参数
OpenAPI 3 核心注解详解 注解 作用 使用位置 示例 @OpenAPIDefinition全局配置(替代 Swagger 2 的ApiInfo) 配置类/启动类 @OpenAPIDefinition(info = @Info(title = "OpenAPI 3 文档", version = "1.0", description = "..."))@Tag标记 Controller 类(替代@Api) Controller 类上 @Tag(name = "用户管理", description = "用户CRUD")@Operation描述方法(替代@ApiOperation) 接口方法上 @Operation(summary = "查询用户", description = "根据ID查用户", tags = {"用户管理"})@Parameter描述单个参数(替代@ApiImplicitParam/@ApiParam) 方法参数前/@Parameters @Parameter(name = "userId", description = "用户ID", required = true, in = ParameterIn.PATH)@Parameters批量描述参数(替代@ApiImplicitParams) 方法上 @Parameters({@Parameter(...), @Parameter(...)})@Schema描述实体类/字段(替代@ApiModel/@ApiModelProperty) 实体类/字段上 类:@Schema(name = "UserDTO", description = "用户参数");字段:@Schema(description = "用户名", required = true, example = "zhangsan") @ApiResponse描述响应(包路径:io.swagger.v3.oas.annotations.responses) 方法上/@ApiResponses @ApiResponse(responseCode = "200", description = "成功", content = @Content(schema = @Schema(implementation = UserDTO.class)))@Hidden忽略元素(替代@ApiIgnore) 类/方法/参数/字段 @Hidden @GetMapping("/test")
OpenAPI 3 完整示例 // 配置类(Spring Boot 3.x) @Configuration public class OpenApi3Config { @Bean public OpenAPI customOpenAPI ( ) { return new OpenAPI ( ) . info ( new Info ( ) . title ( "SpringBoot OpenAPI 3 接口文档" ) . version ( "1.0" ) . description ( "基于Knife4j增强的OpenAPI 3文档" ) ) . components ( new Components ( ) // 全局请求头(如token) . addParameters ( "token" , new Parameter ( ) . name ( "token" ) . description ( "请求令牌" ) . required ( true ) . in ( ParameterIn . HEADER. toString ( ) ) . schema ( new Schema ( ) . type ( "string" ) ) ) ) ; } } // Controller @RestController @RequestMapping ( "/user" ) @Tag ( name= "用户管理接口" , description= "OpenAPI 3 示例接口" ) public class UserController { @GetMapping ( "/{userId}" ) @Operation ( summary= "根据ID查询用户" , description= "仅返回已激活用户,需携带token请求头" ) @Parameters ( { @Parameter ( name= "userId" , description= "用户ID" , required= true , in= ParameterIn . PATH) , @Parameter ( name= "token" , description= "请求令牌" , required= true , in= ParameterIn . HEADER) } ) @ApiResponses ( { @ApiResponse ( responseCode= "200" , description= "查询成功" , content= @Content ( schema= @Schema ( implementation= UserDTO . class ) ) ) , @ApiResponse ( responseCode= "404" , description= "用户不存在" ) , @ApiResponse ( responseCode= "500" , description= "服务器错误" ) } ) public Result < UserDTO > getUser ( @PathVariable Long userId, @RequestHeader String token) { return Result . success ( new UserDTO ( ) ) ; } @PostMapping ( "/save" ) @Operation ( summary= "新增用户" , description= "用户名必填,密码≥6位" ) @ApiResponse ( responseCode= "200" , description= "新增成功" ) public Result < Void > save ( @Parameter ( description= "用户信息" , required= true ) @RequestBody UserDTO userDTO) { return Result . success ( ) ; } } // 实体类 @Schema ( name= "UserDTO" , description= "用户新增请求参数模型" ) public class UserDTO { @Schema ( description= "用户名" , required= true , example= "zhangsan" ) private String username; @Schema ( description= "密码" , required= true , example= "123456" , hidden= true ) private String password; @Schema ( description= "年龄" , required= false , example= "20" ) private Integer age; // getter/setter } 四、Knife4j 专属增强注解 Knife4j 基于 Swagger/SpringDoc 扩展,除了兼容所有原生注解,还新增了分组、权限、文档导出等增强注解,核心如下:
注解 作用 使用位置 示例 @EnableKnife4j启用 Knife4j 增强功能(替代@EnableSwagger2,兼容 OpenAPI 3) 配置类上 @Configuration @EnableKnife4j public class Knife4jConfig {...}@ApiOperationSupportKnife4j 增强的方法注解(排序、忽略参数、多语言等) 接口方法上 @ApiOperationSupport(order = 1, ignoreParameters = "password")@DynamicParameter动态参数注解(适配Map类型参数) 方法/参数上 @DynamicParameters(name = "params", properties = {@DynamicParameter(name = "key", value = "值", example = "test")})@ApiSort接口分组排序(替代@ApiOperationSupport的 order) Controller 类上 @ApiSort(1) @Tag(name = "用户接口")
Knife4j 增强示例(基于 OpenAPI 3) @Configuration @EnableOpenApi // OpenAPI 3 启用 @EnableKnife4j // 启用Knife4j增强 public class Knife4jConfig { @Bean public OpenAPI customOpenAPI ( ) { return new OpenAPI ( ) . info ( new Info ( ) . title ( "Knife4j 增强文档" ) . version ( "1.0" ) ) ; } } @RestController @RequestMapping ( "/user" ) @Tag ( name= "用户管理接口" ) @ApiSort ( 1 ) // 分组排序(1优先显示) public class UserController { @PostMapping ( "/save" ) @Operation ( summary= "新增用户" ) @ApiOperationSupport ( order= 1 , // 方法排序 ignoreParameters= "password" // 忽略密码参数显示 ) public Result < Void > save ( @RequestBody UserDTO userDTO) { return Result . success ( ) ; } // 动态参数(Map入参) @PostMapping ( "/dynamic" ) @Operation ( summary= "动态参数示例" ) @DynamicParameters ( name= "DynamicParam" , properties= { @DynamicParameter ( name= "name" , value= "名称" , example= "测试" ) , @DynamicParameter ( name= "value" , value= "值" , example= "123" ) } ) public Result < Void > dynamic ( @RequestBody Map < String , Object > params) { return Result . success ( ) ; } } 五、关键注意事项 版本兼容 :Spring Boot 2.x 可混用 Swagger 2(springfox)或 OpenAPI 3(springdoc); Spring Boot 3.x 仅支持 OpenAPI 3(springdoc),Knife4j 4.x 适配 Spring Boot 3.x。 敏感信息隐藏 :密码、令牌等字段用@Schema(hidden = true)(OpenAPI 3)或@ApiModelProperty(hidden = true)(Swagger 2)隐藏。 Knife4j 访问地址 :Swagger 2 + Knife4j:http://localhost:8080/doc.html(核心,替代原生swagger-ui.html); OpenAPI 3 + Knife4j:同上,原生地址http://localhost:8080/swagger-ui/index.html。 生产环境关闭 :@Profile ( { "dev" , "test" } ) // 仅开发/测试环境启用 @Configuration @EnableKnife4j public class Knife4jConfig { . . . } 六、核心依赖(Maven) 1. Swagger 2 + Knife4j(Spring Boot 2.x) <!-- Swagger 2 核心 --> < dependency> < groupId> io.springfox</ groupId> < artifactId> springfox-swagger2</ artifactId> < version> 2.9.2</ version> </ dependency> <!-- Knife4j 增强 --> < dependency> < groupId> com.github.xiaoymin</ groupId> < artifactId> knife4j-spring-boot-starter</ artifactId> < version> 2.0.9</ version> </ dependency> 2. OpenAPI 3 + Knife4j(Spring Boot 3.x) <!-- SpringDoc OpenAPI 3 核心 --> < dependency> < groupId> org.springdoc</ groupId> < artifactId> springdoc-openapi-starter-webmvc-ui</ artifactId> < version> 2.2.0</ version> </ dependency> <!-- Knife4j 增强 OpenAPI 3 --> < dependency> < groupId> com.github.xiaoymin</ groupId> < artifactId> knife4j-openapi3-jakarta-spring-boot-starter</ artifactId> < version> 4.4.0</ version> </ dependency> 以上注解覆盖了接口文档生成的所有核心场景(分组、参数、响应、实体、动态参数、权限隐藏等),Knife4j 完全兼容 Swagger 原生注解,优先推荐使用 OpenAPI 3(Swagger 3)+ Knife4j 的组合,适配最新 Spring Boot 版本。