专业的JAVA编程教程与资源

网站首页 > java教程 正文

Spring Boot3 整合 Swagger3 轻松实现超酷在线接口文档展示!

temp10 2025-05-02 13:13:05 java教程 4 ℃ 0 评论

在当今互联网大厂开发的快节奏环境中,高效且清晰的接口文档对于项目的顺利推进至关重要。对于使用 Spring Boot3 进行开发的你来说,是否渴望找到一种便捷的方式来整合 Swagger3,从而轻松实现超酷的在线接口文档展示呢?别着急,本文将为你一一揭晓。

Spring Boot3 与 Swagger3 简介

Spring Boot3

Spring Boot3 整合 Swagger3 轻松实现超酷在线接口文档展示!

Spring Boot3 于 2022 年 11 月 24 日发布,它极大地简化了独立的、生产级别的基于 Spring 应用的创建,你几乎可以做到 “拿来就运行” 。它对 Spring 平台和第三方库持有特定的观点,使得开发者能够以最小的麻烦启动项目,大多数 Spring Boot 应用只需要极少的 Spring 配置。并且,Spring Boot3 支持 Java 17,还引入了 Spring Native 等重要特性,能够将 Spring 程序编译成本地可执行的镜像文件,显著提升启动时间、峰值性能和内存利用率。

Swagger3

Swagger3 是基于 OpenAPI 3 规范的实现。OpenAPI 规范定义了一个标准的、与语言无关的 RESTful API 接口,使得人们和计算机无需访问源代码、文档或通过网络流量检查,就能发现和理解服务的功能。Swagger 提供了一系列工具,如 Swagger Editor(基于浏览器的编辑器,可编写 OpenAPI 规范)、Swagger UI(将 OpenAPI 规范呈现为交互式 API 文档)以及 Swagger Codegen(通过为 OpenAPI 规范定义的任何 API 生成服务器存根和客户端 SDK 来简化构建过程)。目前,Swagger3 是 Swagger 的最新版本,相较于 Swagger2,它配置更少,使用更加方便。

Spring Boot3 整合 Swagger3 的具体步骤

添加 Swagger3 依赖

在 Spring Boot3 项目的 pom.xml 文件中,你需要添加
springdoc-openapi-starter-webmvc-ui 依赖。具体配置如下:

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

配置 Swagger3

在 Spring Boot 应用中,创建一个配置类,例如 OpenApiConfig.java 。在该类中,你可以定义 OpenAPI 相关的配置信息,包括基础 URL、标题、版本、作者联系信息、描述、许可证等。示例代码如下:

package com.example.config;

import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

@Configuration
public class OpenApiConfig {

    @Value("${springdoc.version}")
    private String apiVersion;

    @Value("${springdoc.title}")
    private String apiTitle;

    @Value("${springdoc.description}")
    private String apiDescription;

    @Value("${springdoc.termsOfServiceUrl}")
    private String termsOfServiceUrl;

    @Value("${springdoc.contact.name}")
    private String contactName;

    @Value("${springdoc.contact.url}")
    private String contactUrl;

    @Value("${springdoc.contact.email}")
    private String contactEmail;

    @Value("${springdoc.license.name}")
    private String licenseName;

    @Value("${springdoc.license.url}")
    private String licenseUrl;

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
              .info(new Info()
                  .title(apiTitle)
                  .version(apiVersion)
                  .description(apiDescription)
                  .termsOfService(termsOfServiceUrl)
                  .contact(new Contact()
                      .name(contactName)
                      .url(contactUrl)
                      .email(contactEmail))
                  .license(new License()
                      .name(licenseName)
                      .url(licenseUrl)));
    }
}

这里的配置信息可以通过在 application.properties 或 application.yml 文件中进行配置,例如

springdoc.version=1.0
springdoc.title=My API
springdoc.description=This is my API description
springdoc.termsOfServiceUrl=https://example.com/terms
springdoc.contact.name=John Doe
springdoc.contact.url=https://example.com/contact
springdoc.contact.email=john@example.com
springdoc.license.name=MIT License
springdoc.license.url=https://opensource.org/licenses/MIT

如果你使用的是 Spring Webflux,还需要添加相应的依赖和配置。对于 Spring Webflux 项目,添加
springdoc-openapi-starter-webflux-ui依赖:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
    <version>2.0.3</version>
</dependency>

然后配置 Swagger3,示例配置类如下:

package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.config.EnableWebFlux;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;

@Configuration
@EnableWebFlux
public class OpenApiWebFluxConfig {

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
              .info(new Info()
                  .title("WebFlux API")
                  .version("1.0")
                  .description("This is a WebFlux API with Swagger3"));
    }
}

使用 Swagger 注解

在你的控制器类和方法上,可以使用 Swagger 的注解来提供更多的接口信息和自定义。例如:

package com.example.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;

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

    @GetMapping("/example")
    @Operation(summary = "Get example data", description = "Returns example data from the server")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "Successfully retrieved data",
            content = @Content(schema = @Schema(implementation = String.class))),
        @ApiResponse(responseCode = "404", description = "Data not found",
            content = @Content)})
    public String getExampleData() {
        return "This is example data";
    }
}

访问 Swagger UI

当你完成上述配置并启动 Spring Boot 应用后,就可以通过浏览器访问 Swagger UI 来查看和测试你的 API 接口文档了。默认情况下,访问路径为
http://localhost:8080/swagger - ui/ 或
http://localhost:8080/swagger - ui/index.html (请根据你的实际端口号进行替换)。在 Swagger UI 界面中,你可以清晰地看到各个接口的信息,包括接口路径、请求方法、参数、响应等,并且还可以直接在界面上进行接口测试。

总结

通过以上步骤,你已经成功地在 Spring Boot3 项目中整合了 Swagger3,实现了在线接口文档展示。这不仅提高了开发效率,使得前后端开发人员能够更清晰地理解接口,还方便了项目的维护和管理。在实际项目中,你可以根据具体需求进一步优化 Swagger 的配置,例如添加安全认证、自定义文档样式等。现在,赶紧行动起来,让你的项目拥有超酷的在线接口文档展示吧!

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表