整合Swagger

本文介绍了如何在Spring Boot项目中整合Swagger,实现接口文档的自动化生成与管理。通过添加依赖、配置Swagger类以及使用注解,开发者可以方便地创建、调试和分组接口文档。此外,还讲解了如何根据环境条件开关Swagger,确保生产环境的安全。

整合Swagger

在现在的web开发中,前后端分离的开发模式大行其道,前端负责页面渲染,并发送请求到后端服务器请求数据,后端负责数据访问和处理,然后返回数据给前端

在前后端开发的模式中,接口的定义在协同开发中就非常重要,前端开发人员需要清晰地知道后端接口的用途,需要的参数和返回的数据,因此在开发中需要一份接口文档。Swagger是一款流行的Api框架,他可以定义Api接口的参数和返回值,并且支持同步更新和在线调试,解决了这个问题

基本使用

使用Swagger,需要导入Swagger的starter依赖,本文以Swagger3为例,Swagger2的用法和Swagger3会有少许不同

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

配置Swagger配置类,将@EnableOpenApi注解添加在配置类或者启动类上

在容器中添加一个ApiInfo组件和Docket组件,ApiInfo组件用于描述项目的内容,作者以及License等信息,Docket组件用于设置接口文档需要扫描的接口

@Configuration
@EnableOpenApi
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(ApiInfo apiInfo) {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo)
                .select()
                // 扫描接口,支持按包扫描,按注解扫描,全部扫描,全部不扫描
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
            	// 过滤的路径,支持按路径匹配,按正则表达式匹配,全部匹配,全部不匹配
                .paths(PathSelectors.any())
                .build();
    }

    @Bean
    public ApiInfo apiInfo() {
        Contact contact = new Contact("葱酱", "https://blog.youkuaiyun.com/blackball1998", "425017255@qq.com");
        return new ApiInfoBuilder()
                .title("我的项目")
                .description("我的项目介绍")
                .version("1.0")
                .termsOfServiceUrl("https://blog.youkuaiyun.com/blackball1998")
                .contact(contact)
                .license("Apache 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0")
                .build();
    }

}

在接口类中添加@Api注解,设置接口类的作用,在接口上添加@ApiOperation注解,设置接口的作用

@Api(tags = "测试相关类")
@RestController
public class MyController {

    @ApiOperation(value = "测试接口", notes = "备注:这是一个测试接口")
    @GetMapping("/test")
    public String test(@RequestParam("name") String name) {
        return "success";
    }
}

设置完成后,启动项目,访问项目下的**/swagger-ui/index.html**地址,可以得到Swagger自动生成的文档页面,页面中有项目的描述信息,包括在配置类中设置的个人信息

在这里插入图片描述

扫描到的接口类也会出现在页面中,点开可以查看接口的请求方式,参数和返回值等信息

在这里插入图片描述

点击接口文档中的Try it out按键,还可以发送请求进行调试

在这里插入图片描述

在这里插入图片描述

添加参数和返回值说明

如果接口的参数或者返回值是用实体类表示的,我们还可以在参数类和返回类上添加参数和返回值的信息,比如我们的接口使用一个TestReqVO对象来接收,然后用一个TestResVO对象来返回

在VO类上添加@ApiModel注解,设置参数和返回的说明,然后在类的属性上添加@ApiModelProperty注解,设置每一个参数属性和返回值属性的说明

@Data
@ApiModel("测试接口参数")
public class TestReqVO {

    @ApiModelProperty("名字")
    String name;
    @ApiModelProperty("编号")
    String code;
}
@Data
@ApiModel("测试接口返回")
public class TestResVO {

    @ApiModelProperty("状态")
    String state;
    @ApiModelProperty("住址")
    String address;
    @ApiModelProperty("邮箱")
    String email;
}

只要在被Swagger扫码到的接口使用了这个VO作为参数或者返回值,Swagger就会将VO的信息添加在文档中

@Api(tags = "测试相关类")
@RestController
public class MyController {

    @GetMapping("/test")
    @ApiOperation(value = "测试接口", notes = "备注:这是一个测试接口")
    public TestResVO test(TestReqVO vo) {
        return new TestResVO();
    }
}

在这里插入图片描述

在这里插入图片描述

接口文档分组

在开发中,往往后台由多个人来开发,每个人开发自己的模块。Swagger支持文档分组的功能,每个人将自己的接口放在自己的组中,分别编写各自的接口说明文档

使用文档分组,只需要在Swagger配置类中添加多个Docket组件,每个组件设置不同的Bean名称,然后在不同的Docket中扫描不同的接口,这样就可以以每个Docket为一组分组

@Configuration
@EnableOpenApi
public class SwaggerConfig {

    @Bean
    public Docket docketA(ApiInfo apiInfo) {
        return new Docket(DocumentationType.OAS_30)
                .groupName("groupA")
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.blackball.groupA.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    @Bean
    public Docket docketB(ApiInfo apiInfo) {
        return new Docket(DocumentationType.OAS_30)
                .groupName("groupB")
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.blackball.groupB.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    @Bean
    public Docket docketC(ApiInfo apiInfo) {
        return new Docket(DocumentationType.OAS_30)
                .groupName("groupC")
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.blackball.groupC.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    @Bean
    public ApiInfo apiInfo() {
        Contact contact = new Contact("葱酱", "https://blog.youkuaiyun.com/blackball1998", "425017255@qq.com");
        return new ApiInfoBuilder()
                .title("我的项目")
                .description("我的项目介绍")
                .version("1.0")
                .termsOfServiceUrl("https://blog.youkuaiyun.com/blackball1998")
                .contact(contact)
                .license("Apache 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0")
                .build();
    }

}

打开Swagger页面,可以看到文档右上角有一个分组下拉框,可以按组显示不同的接口

在这里插入图片描述

根据环境开启关闭文档

一般情况下,接口文档只需要在开发阶段开放给开发人员阅读,而线上环境需要关闭文档,我们可以在IOC容器中获取Environment组件,用于判断当前的项目运行环境,然后使用Docket类的enable方法来自动开启关闭Swagger

@Configuration
@EnableOpenApi
public class SwaggerConfig {

    @Bean
    public Docket docket(ApiInfo apiInfo, Environment environment) {
        Profiles profiles = Profiles.of("dev", "test");
        boolean isEnable = environment.acceptsProfiles(profiles);
        return new Docket(DocumentationType.OAS_30)
                .enable(isEnable)
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    @Bean
    public ApiInfo apiInfo() {
        Contact contact = new Contact("葱酱", "https://blog.youkuaiyun.com/blackball1998", "425017255@qq.com");
        return new ApiInfoBuilder()
                .title("我的项目")
                .description("我的项目介绍")
                .version("1.0")
                .termsOfServiceUrl("https://blog.youkuaiyun.com/blackball1998")
                .contact(contact)
                .license("Apache 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0")
                .build();
    }

}

设置项目环境为线上环境

spring:
  profiles:
    active: pro

这时候打开Swagger文档,发现由于环境条件过滤,Swagger文档已经关闭

在这里插入图片描述

虽然没有直接关于Spring Boot 3.5.7版本整合Swagger的内容,但可以参考普遍的Spring Boot整合Swagger的思路,结合版本特性来推测步骤。 ### 添加依赖包 在项目的`pom.xml`文件中添加Swagger相关依赖。通常需要添加Swagger 3的核心依赖和Springfox的依赖。以下是示例代码: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> ``` ### 配置Swagger 创建一个配置类来配置Swagger。在这个类中,可以定义Swagger的基本信息,如API文档的标题、描述、版本等。以下是示例代码: ```java 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.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.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot 3.5.7整合Swagger API文档") .description("API接口文档描述") .version("1.0.0") .build(); } } ``` ### 修改Spring Boot路径配置规则 如果遇到路径匹配问题,可能需要修改Spring Boot的路径配置规则。参考Spring Boot 2.7.9的配置,修改成`ant_path_matcher`路径配置规则。在`application.properties`或`application.yml`中添加以下配置: ```yaml spring: mvc: pathmatch: matching-strategy: ant_path_matcher ``` ### 测试 启动Spring Boot应用程序,访问Swagger UI界面。通常Swagger UI的访问地址为`http://localhost:端口号/swagger-ui/index.html`。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值