Swagger配置类实战

463 阅读2分钟

在开发Spring Boot项目时,生成API文档是一个常见的需求。Swagger是一个流行的工具,可以帮助我们自动生成规范化、可交互的API文档。下面是一个使用Swagger配置的示例,以帮助你快速入门。

步骤 1:添加Swagger依赖

在你的项目的构建文件(例如pom.xmlbuild.gradle)中,添加Swagger的依赖。这里使用Swagger 3版本:

dependencies {
    // 其他依赖...
    implementation 'io.springfox:springfox-boot-starter:3.0.0'
}

步骤 2:创建Swagger配置类

创建一个Java类(例如SwaggerConfig),并使用@Configuration@EnableSwagger2注解将其标记为配置类,并启用Swagger支持:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
                .groupName("核心开发组") // 设置分组名称
                .select()
                .apis(RequestHandlerSelectors.basePackage("top.keepheartbeat.demo.controller")) // 设置扫描的控制器包
                .paths(PathSelectors.any()) // 设置请求的过滤路径
                .build()
                .apiInfo(apiInfo())
                .enable(true); // 是否开启Swagger
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("XX项目 API 文档") // 设置文档标题
                .description("这是一个示例API文档") // 设置文档描述
                .version("0.0.1 Beta") // 设置文档版本号
                .termsOfServiceUrl("https://gitee.com/nimi_snake/bc09") // API的服务条款URL
                .license("Apache 2.0")
                .contact(new Contact("偷瓜的猹", "keepheartbeat.top", "297435887@qq.com")) // API相关的联系人信息,包括姓名、URL、电子邮件等
                .build();
    }
}

在上述示例中,我们创建了一个SwaggerConfig类,并使用@Configuration@EnableSwagger2注解进行标记和启用Swagger支持。

api()方法中,我们创建了一个Docket实例,设置了API文档的基本信息、分组名称、扫描的控制器包和请求路径过滤器。

apiInfo()方法用于设置API文档的详细信息,包括标题、描述、版本号、服务条款URL、许可证和联系人信息。

步骤 3:访问API文档

在项目启动后,你可以通过访问以下URL来查看生成的API文档:

http://localhost:8080/swagger-ui/

这将打开Swagger UI界面,显示你的API文档的详细信息和交互式功能。

结论

通过按照上述步骤,你可以轻松地使用Swagger配置Spring Boot项目的API文档。在配置类中,你可以根据需要定制API文档的基本信息,并通过Swagger UI来查看和测试API。这样,你的API文档将更加规范、易于理解和使用。

希望本文能够帮助你快速上手使用Swagger生成API文档。如有任何疑问,请随时在下方留言。感谢阅读!