swagger文档生成和测试

本文介绍了swagger2在Spring Boot项目中的使用方法。首先需在pom中加入两个依赖,接着新建swagger配置类,启动工程后访问localhost//swagger-ui.html即可。还说明了具体使用时,如@Api、@ApiOperation等注解的配置,以及返回参数实体类和返回约定的设置。

swagger2是一个在线生成文档和测试功能的软件,使用很简单,大概说一下步骤。

一、在pom中加入两个依赖:

<dependency>

    <groupId>io.springfox</groupId>

    <artifactId>springfox-swagger2</artifactId>

    <version>2.2.2</version>

</dependency>

<dependency>

    <groupId>io.springfox</groupId>

    <artifactId>springfox-swagger-ui</artifactId>

    <version>2.2.2</version>

</dependency>

2、新建swagger配置类:

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

import java.util.ArrayList;
import java.util.List;


@Configuration
@EnableSwagger2
public class SwaggerConfig {

     public class Swagger2 {
     
         @Bean
         public Docket createRestApi() {
             
             ParameterBuilder tokenPar = new ParameterBuilder();
             List<Parameter> pars = new ArrayList<>();
             tokenPar.name("Authorization").description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
             pars.add(tokenPar.build());
     
             return new Docket(DocumentationType.SWAGGER_2)
                     .apiInfo(apiInfo())
                     .select()
                     .apis(RequestHandlerSelectors.basePackage("com.zp"))   
 //根据自己具体要扫描api的路径,就是接口路径。
                     .paths(PathSelectors.any())                   // 对所有路径进行监控
                     .build()
                     .globalOperationParameters(pars);
         }
     
         private ApiInfo apiInfo() {
             return new ApiInfoBuilder()
                     .title("Spring Boot中使用Swagger2构建RESTful APIs")
                     .description("springboot项目接口文档")
                     .termsOfServiceUrl("")
                     .contact("iamapsycho")
                     .version("1.0")
                     .build();
         }
     }
}

三、启动工程,访问localhost//swagger-ui.html即可。

四、具体使用

配置swagger还可以很精细,可以根据自己需要进行配置,比如扫描的具体包等。在代码中使用swagger功能,即可生成文档,具体百度很多。

1、@Api:请求类的说明:

       tags:"说明该类的作用" 。value="该参数没什么意义,跟tags一样,所以不配置。

例子:@Api(tags = "消费分析")

2、@ApiOperation

      value:表示的是方法名称

      notes:表示的是方法描述,如接口描述

例子:@ApiOperation(value="商户热力地图",notes="热力地图,展示消费区域情况。")

3、@ApiImplicitParams:请求参数说明:

       name = 参数字符名称

       required :参数是否必须
       dataType:参数类型,默认String,其它值dataType="int"

       value :参数中文备注说明

例子:@ApiImplicitParams({
            @ApiImplicitParam(name = "unitCode", value = "99全部", required = false,
                    paramType = "query", dataType = "String")

4、返回参数实体类:

@ApiModel在实体类的方法上:

@ApiModelProperty:属性类的实体上面,属性上面,说明属性的含义。

@ApiModel(description= "返回响应数据") 

@ApiModelProperty(value = "是否成功")

5、返回约定(可以不写,约定写在公共文件头就行):


@ApiResponses:方法返回对象的说明
@ApiResponse:每个参数的说明


        code:数字,例如400
        message:信息,例如"请求参数没填好"
        response:抛出异常的类

例子:

@ApiResponses({
        @ApiResponse(code = 400, message = "请求参数没填好"),
        @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
    }) 

注释:

可参考:https://blog.youkuaiyun.com/sanyaoxu_2/article/details/80555328

### 使用Swagger自动生成API测试文档 #### 配置环境与引入依赖 为了能够顺利使用Swagger来自动生成API测试文档,首先需要确保项目环境中已经包含了必要的依赖项。对于Java项目而言,在`pom.xml`文件中加入如下依赖: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> ``` 这些依赖允许Spring应用程序集成并展示由Swagger生成的API文档[^2]。 #### 编写Swagger配置类 创建一个新的Java类用于定义Swagger的相关设置。此类需标注为@Configuration以告知Spring这是一个配置组件,并通过@EnableSwagger2启用Swagger功能。在此基础上,还需提供一个返回Docket实例的方法作为@Bean注入到IoC容器中,以便于后续操作。此方法内部主要完成对API基本信息(如标题、版本号等)、扫描路径以及是否开放UI界面等方面的设定。 ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; 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 docket() { return new Docket(DocumentationType.SWAGGER_2) .enable(true) // 是否开启swagger,默认true .apiInfo(apiInfo()) .select() .apis(requestHandlerSelectors -> requestHandlerSelectors.basePackage("com.example.controller")) .paths(path -> path.startsWith("/api/")) // 只显示/api开头的接口 .build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("示例项目的API文档") .description("这里是关于本项目的API描述...") .version("1.0") .build(); } } ``` 上述代码片段展示了如何构建一个基本的Swagger配置类,其中`.select()`部分指定了哪些控制器下的接口会被纳入到最终生成的文档里;而`.apiInfo()`则用来定制化页面顶部所呈现的信息条目。 #### 启动服务查看效果 当一切准备就绪后,重启应用服务器使新的配置生效。此时打开浏览器输入类似于`http://localhost:8080/swagger-ui.html`这样的URL即可看到基于当前工程结构动态渲染出来的交互式API文档页面了[^4]。 对于采用Gin框架开发的应用程序来说,则可通过添加特定路由规则的方式快速实现相同目的: ```go r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) ``` 这段简单的Go语言代码实现了将所有匹配模式`/swagger/*any`的请求转发给内置处理函数的功能,从而达到暴露Swagger UI的目的[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kunzai6

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值