springboot项目中与接口文档有关的注解

在 Spring Boot 项目中,Swagger(主流分为 Swagger 2/Springfox 和 OpenAPI 3/SpringDoc) 是接口文档生成的核心框架,而 Knife4j 是基于 Swagger 的增强版(完全兼容 Swagger 注解,同时新增少量专属增强注解)。以下是完整的注解分类及详解,包含 Swagger 2、OpenAPI 3(Swagger 3)、Knife4j 增强注解,附使用场景和示例。

一、核心说明

框架/版本 依赖核心 注解归属包 备注
Swagger 2(Springfox) springfox-swagger2 io.swagger.annotations 老版本主流,Spring Boot 2.6+ 需适配
OpenAPI 3(Swagger 3) springdoc-openapi io.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 完整示例
java 复制代码
// 配置类
@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 完整示例
java 复制代码
// 配置类(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 {...}
@ApiOperationSupport Knife4j 增强的方法注解(排序、忽略参数、多语言等) 接口方法上 @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)
java 复制代码
@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();
    }
}

五、关键注意事项

  1. 版本兼容

    • Spring Boot 2.x 可混用 Swagger 2(springfox)或 OpenAPI 3(springdoc);
    • Spring Boot 3.x 仅支持 OpenAPI 3(springdoc),Knife4j 4.x 适配 Spring Boot 3.x。
  2. 敏感信息隐藏

    • 密码、令牌等字段用 @Schema(hidden = true)(OpenAPI 3)或 @ApiModelProperty(hidden = true)(Swagger 2)隐藏。
  3. Knife4j 访问地址

    • Swagger 2 + Knife4j:http://localhost:8080/doc.html(核心,替代原生 swagger-ui.html);
    • OpenAPI 3 + Knife4j:同上,原生地址 http://localhost:8080/swagger-ui/index.html
  4. 生产环境关闭

    java 复制代码
    @Profile({"dev", "test"}) // 仅开发/测试环境启用
    @Configuration
    @EnableKnife4j
    public class Knife4jConfig {...}

六、核心依赖(Maven)

1. Swagger 2 + Knife4j(Spring Boot 2.x)
xml 复制代码
<!-- 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)
xml 复制代码
<!-- 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 版本。

相关推荐
利刃大大2 小时前
【JavaSE】十一、Stack && Queue && Deque && PriorityQueue && Map && Set
java·数据结构·优先级队列··哈希表·队列·集合类
小码哥0682 小时前
家政服务管理-家政服务管理平台-家政服务管理平台源码-家政服务管理平台java代码-基于springboot的家政服务管理平台
java·开发语言·spring boot·家政服务·家政服务平台·家政服务系统·家政服务管理平台源码
Java爱好狂.2 小时前
复杂知识简单学!Springboot加载配置文件源码分析
java·spring boot·后端·spring·java面试·后端开发·java程序员
Array*2 小时前
java实现word中插入附件(支持所有文件格式)
java·开发语言·word·poi·ole
invicinble2 小时前
easyexcel的基本使用
spring boot
Donald_brian2 小时前
线程同步
java·开发语言·jvm
全靠bug跑2 小时前
Nacos 入门实战:部署、服务注册与发现全指南
java·spring cloud·docker·nacos
郑州光合科技余经理2 小时前
技术视角:海外版一站式同城生活服务平台源码解析
java·开发语言·uni-app·php·排序算法·objective-c·生活
喵了meme2 小时前
Linux学习日记19:线程同步与互斥锁
java·jvm·学习