SpringBoot3使用Springdoc OpenAPI集成接口文档

步骤1:添加依赖

pom.xml中添加Springdoc OpenAPI的依赖:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.0.0</version>
</dependency>

步骤2:基本配置

1. 关于文档信息定制的配置

yaml文件
springdoc:
  api-docs:
    path: /api-docs  # 配置 OpenAPI 文档的路径
  swagger-ui:
    path: /swagger-ui.html  # 配置 Swagger UI 的路径
    enabled: true  # 启用 Swagger UI
    
  # 定制文档基本信息
  info:
    title: API 文档标题  # 设置文档标题
    description: API 文档描述  # 设置文档描述
    version: 1.0.0  # 设置 API 版本
    terms-of-service: https://example.com/terms  # 服务条款 URL
    
    # 关于开发者
    contact:
      name: 开发者姓名  # 开发者联系人姓名
      url: https://example.com/contact  # 联系方式 URL
      email: dev@example.com  # 开发者联系邮箱
      
    # 关于许可证
    license:
      name: Apache 2.0  # 许可证名称
      url: https://www.apache.org/licenses/LICENSE-2.0.html  # 许可证 URL
      
  # 定制服务器基本信息
  servers:
    - url: http://localhost:8080  # 服务器 URL
      description: 本地服务器  # 服务器描述
    - url: https://api.example.com  # 服务器 URL
      description: 生产服务器  # 服务器描述
      
  # 定制外部文档信息
  external-docs:
    description: 外部文档描述  # 外部文档描述
    url: https://example.com/docs  # 外部文档 URL
properties文件
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
springdoc.swagger-ui.enabled=true
springdoc.info.title=API 文档标题
springdoc.info.description=API 文档描述
springdoc.info.version=1.0.0
springdoc.info.terms-of-service=https://example.com/terms
springdoc.info.contact.name=开发者姓名
springdoc.info.contact.url=https://example.com/contact
springdoc.info.contact.email=dev@example.com
springdoc.info.license.name=Apache 2.0
springdoc.info.license.url=https://www.apache.org/licenses/LICENSE-2.0.html
springdoc.servers[0].url=http://localhost:8080
springdoc.servers[0].description=本地服务器
springdoc.servers[1].url=https://api.example.com
springdoc.servers[1].description=生产服务器
springdoc.external-docs.description=外部文档描述
springdoc.external-docs.url=https://example.com/docs

2. 自定义配置类

import org.springdoc.core.customizers.OpenApiCustomizer;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.servers.Server;

@Configuration
public class OpenApiConfig {

    // OpenAPI类用于定制全局文档信息
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
            // 定制文档基本信息
            .info(new Info()
                  //关于文档信息
                .title("API 文档标题")
                .description("API 文档描述")
                .version("1.0.0")
                .termsOfService("https://example.com/terms")
                  
                  //关于作者
                .contact(new Contact()
                    .name("开发者姓名")
                    .url("https://example.com/contact")
                    .email("dev@example.com"))
                  
                  //关于许可证
                .license(new License()
                    .name("Apache 2.0")
                    .url("https://www.apache.org/licenses/LICENSE-2.0.html")))
            
            //配置服务器信息
            .servers(List.of(
                new Server().url("http://localhost:8080").description("本地服务器"),
                new Server().url("https://api.example.com").description("生产服务器")))
            
            //配置外部文档信息
            .externalDocs(new ExternalDocumentation()
                .description("外部文档描述")
                .url("https://example.com/docs"));
    }

    // GroupedOpenApi类用于API分组
    @Bean
    public GroupedOpenApi publicApi() {
        return GroupedOpenApi.builder()
            .group("public")
            .pathsToMatch("/api/**")
            .build();
    }

    // OpenApiCustomizer类用于自定义OpenAPI对象,比如全局添加头部信息。
    @Bean
    public OpenApiCustomizer customerGlobalHeaderOpenApiCustomizer() {
        return openApi -> openApi.info(
            new Info().title("自定义 API 文档")
                .description("自定义 API 文档描述")
                .version("1.0.0")
        );
    }
}
说明
  1. OpenAPI:用于设置全局的 API 文档信息,例如标题、描述、版本、联系信息、许可证、服务器和外部文档等。
  2. GroupedOpenApi:用于将 API 分组。例如,可以将公共 API 和私有 API 分开。
  3. OpenApiCustomizer 接口:用于自定义 OpenAPI 对象,例如全局添加头部信息等

步骤3:使用注解

Springdoc OpenAPI使用一系列的注解来增强和定制API文档。常用的注解包括@Operation@Parameter@Schema等。

在控制器方法上使用注解
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;

@RestController
@RequestMapping("/api")
public class UserController {

    @Operation(summary = "获取用户信息", description = "根据用户ID获取用户详细信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功"),
        @ApiResponse(responseCode = "404", description = "用户未找到")
    })
    @GetMapping("/users/{id}")
    public User getUserById(@PathVariable Long id) {
        // 实现获取用户的逻辑
        return new User();
    }

    @Operation(summary = "创建新用户", description = "创建一个新的用户")
    @PostMapping("/users")
    public User createUser(@RequestBody CreateUserRequest request) {
        // 实现创建用户的逻辑
        return new User();
    }
}
在实体类上使用注解
import io.swagger.v3.oas.annotations.media.Schema;

@Schema(description = "用户实体")
public class User {
    @Schema(description = "用户ID", example = "1")
    private Long id;

    @Schema(description = "用户名", example = "john_doe")
    private String username;

    @Schema(description = "用户年龄", example = "25")
    private Integer age;

    // getters and setters
}

步骤4:访问在线接口文档

启动Spring Boot应用后,访问http://localhost:8080/swagger-ui.html可以查看生成的API文档界面。

注解详解

1. @Operation

@Operation注解用于描述一个具体的API操作。它可以添加到控制器的方法上,用于定义操作的基本信息

属性:

  • summary:操作的简要描述。
  • description:操作的详细描述。
  • tags:与操作相关的标签。
  • operationId:操作的唯一标识符。
  • parameters:操作的参数列表。
  • responses:操作的响应列表。

示例:

@Operation(
    summary = "获取用户信息",
    description = "根据用户ID获取用户详细信息",
    tags = {"用户操作"},
    operationId = "getUserById"
)
@RequestMapping("/users")
public User getUserById(@PathVariable Long id) {
    // 实现逻辑
}

2. @Parameter

@Parameter注解用于描述方法参数。它可以添加到控制器方法的参数上

属性:

  • name:参数名。
  • description:参数描述。
  • required:是否必需参数。
  • in:参数所在位置(query、header、path、cookie)。

示例:

@Operation(summary = "删除用户")
@DeleteMapping("/users/{id}")
public void deleteUser(@Parameter(description = "用户ID", required = true) @PathVariable Long id){
    // 实现逻辑
}

3. @RequestBody

@RequestBody注解用于描述请求体中的内容。它通常添加到方法的参数上,标识该参数是请求体。

属性:

  • description:请求体的描述。
  • required:是否必需。

示例:

@Operation(summary = "创建新用户")
@PostMapping("/users")
public User createUser(@RequestBody(description = "用户创建请求", required = true) CreateUserRequest request)
{
    // 实现逻辑
}

4. @ApiResponse 和 @ApiResponses

@ApiResponse注解用于描述单个API响应,而@ApiResponses注解用于包含多个@ApiResponse注解。

属性:

  • responseCode:响应代码。
  • description:响应描述。
  • content:响应内容。

示例:

@Operation(summary = "获取用户信息")
@ApiResponses(value = {
    @ApiResponse(responseCode = "200", description = "成功获取用户信息"),
    @ApiResponse(responseCode = "404", description = "用户未找到")
})
@GetMapping("/users/{id}")
public User getUserById(@PathVariable Long id) {
    // 实现逻辑
}

5. @Schema

@Schema注解用于描述实体类及其属性。它可以添加到类和属性上。

属性:

  • description:模型或属性的描述。
  • example:示例值。
  • required:必需属性。
  • hidden:是否隐藏属性。

示例:

@Schema(description = "用户实体")
public class User {
    @Schema(description = "用户ID", example = "1")
    private Long id;

    @Schema(description = "用户名", example = "john_doe")
    private String username;

    @Schema(description = "用户年龄", example = "25")
    private Integer age;

    // getters and setters
}

6. @Tag

@Tag注解用于为API操作分组。可以添加到类或方法上。

属性:

  • name:标签名。
  • description:标签描述。

示例:

@Tag(name = "用户操作", description = "与用户相关的操作")
@RestController
@RequestMapping("/api")
public class UserController {
    // 控制器方法
}

7. @Hidden

@Hidden注解用于隐藏API操作、参数或模型属性,不在生成的文档中显示

示例:

@Hidden
@GetMapping("/hidden")
public void hiddenMethod() {
    // 实现逻辑
}

8. @Content 和 @MediaType

@Content注解用于描述请求或响应的内容,而@MediaType注解用于指定内容类型

示例:

@Operation(summary = "创建新用户")
@ApiResponses(value = {
    @ApiResponse(responseCode = "201", description = "用户创建成功",
        		 content = @Content(mediaType = "application/json",
      								schema = @Schema(implementation = User.class)
                 )
              )
})
@PostMapping("/users")
public User createUser(@RequestBody CreateUserRequest request) {
    // 实现逻辑
}
要在Spring Boot 3中集成springdoc 2,你可以按照以下步骤进行操作: 1. 添加依赖项:在你的项目的构建文件(例如 pom.xml)中,添加以下依赖项(请替换版本号为最新版本): ```xml <dependencies> <!-- Spring Boot Web Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Springdoc OpenAPI --> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-core</artifactId> <version>1.5.9</version> </dependency> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.5.9</version> </dependency> </dependencies> ``` 2. 配置Swagger UI:在你的应用程序配置类上添加 `@EnableOpenApi` 注解,启用Springdoc OpenAPI。 ```java import org.springframework.context.annotation.Configuration; import org.springdoc.api.annotations.EnableOpenApi; @Configuration @EnableOpenApi public class OpenApiConfig { } ``` 3. 在浏览器中访问Swagger UI:启动你的应用程序后,在浏览器中访问 `http://localhost:8080/swagger-ui.html`,你将看到生成的API文档。 请注意,上述步骤是基于Spring Boot 2.x版本的。如果你的项目使用的是Spring Boot 3.x版本,可能需要更新springdoc-openapi-core和springdoc-openapi-ui的版本以适配Spring Boot 3。你可以查看springdoc的官方文档以获取更多信息和最新版本。 希望这能帮助你集成springdoc 2到你的Spring Boot 3项目中,如果你有任何其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值