API接口管理Swagger 2的使用及注解介绍(Spring boot 2.6.4 + Springfox 3)

一、简介

Swagger 是一套围绕Open API规范构建的开源工具,可以帮助设计,构建,记录和使用REST API。

二、Swagger 工具包含的组件

1. Swagger Editor

基于浏览器编译器,可以在里面编写Open API规范。类型Markdown具有实时预览描述文件的功能。

2. Swagger UI

将Open API规范呈现为交互式API文档。用可视化UI展示描述文件。

3. Swagger Codegen:

将OpenAPI规范生成为服务器存根和客户端库。通过Swagger Codegen可以将描述文件生成html格式和cwiki形式的接口文档,同时也可以生成多种语言的客户端和服务端代码。

4. Swagger Inspector

和Swagger UI有点类似,但是可以返回更多信息,也会保存请求的实际参数数据。

5. Swagger Hub

集成了上面所有项目的各个功能,可以以项目和版本为单位,将描述文件上传到Swagger Hub中。在Swagger Hub中可以完成上面项目的所有工作,需要注册账号,分免费版和收费版。

三、Spring Boot 集成Swagger

1、pom文件中导入Springfox Swagger2与Springfor Swagger UI(注意Springfox3以上和之前版本导入的pom区别)

		<!-- Springfox 3 导入以下依赖 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

		<!-- Springfox 3 以下导入以下依赖 -->
        <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>

2、在Spring Boot启动类上添加开启Swagger的注解

@SpringBootApplication
//@EnableSwagger2   # Springfox3 之前的版本使用@EnableSwagger2
@EnableOpenApi      # Springfox3 使用@EnableOpenApi
public class SwaggerExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SwaggerExampleApplication.class, args);
    }

}

3、修改SpringMVC路径匹配规则(Spring Boot 2.6之前省略此步骤)

由于Spring Boot 2.6 请求路径与 Spring MVC 处理映射匹配的默认策略已从AntPathMatcher更改为PathPatternParser。所以需要设置spring.mvc.pathmatch.matching-strategy为ant-path-matcher来改变它。

在配置文件application.properties文件中添加以下代码(Spring Boot 2.6之前不需要此操作)

spring.mvc.pathmatch.matching-strategy=ant_path_matcher

4、启动项目,测试运行是否正常

首先启动Spring Boot项目,通过以下网址访问,端口号根据自己的项目详细修改
Springfox 3之后的版本访问 http://localhost:8080/swagger-ui/index.html
Springfox 3之前的版本访问 http://localhost:8080/swagger-ui.html
出现以下界面表示集成成功
在这里插入图片描述

四、Swagger 配置

application.properties 文件内容

spring.application.name=Swagger Demo
spring.application.version=1.1
spring.application.description=Demo project for Spring Boot

spring.mvc.pathmatch.matching-strategy=ant_path_matcher

nature.restApi.enabled=true

配置类如下

package com.example.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootVersion;
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.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;

@Configuration
public class SwaggerConfiguration {

    /**
     * 是否开启swagger,生产环境一般关闭,所以这里定义一个变量
     */
    @Value("${nature.restApi.enabled}")
    private Boolean enable;

    /**
     * 项目应用名
     */
    @Value("${spring.application.name}")
    private String applicationName;

    /**
     * 项目版本信息
     */
    @Value("${spring.application.version}")
    private String applicationVersion;

    /**
     * 项目描述信息
     */
    @Value("${spring.application.description}")
    private String applicationDescription;

    /**
     * 创建Docket类型的对象,并使用spring容器管理。
     * Docket是Swagger中的全局配置对象。
     * @return
     */
    @Bean
    Docket docket(){
        return new Docket(DocumentationType.OAS_30)
                //将servlet路径映射(如果有)添加到apis基本路径
                .pathMapping("/")
                // 定义是否开启swagger,false为关闭,可以通过变量控制
                .enable(enable)
                .select()
                //配置需要扫描的controller位置
                .apis(RequestHandlerSelectors
                        .basePackage("com.example"))
                //配置路径
                .paths(PathSelectors.any())
                //构建
                .build()
                //文档信息
                .apiInfo(new ApiInfoBuilder()
                        //标题
                        .title(applicationName + " RESTful API 文档")
                        //版本
                        .version("Application Version: " + applicationVersion + ", " +
                                "Spring Boot Version: " + SpringBootVersion.getVersion())
                        //描述
                        .description(applicationDescription)
                        //联系人信息
                        .contact(new Contact("馨诚科技",//名字
                                "http://www.899pl.com/",//网址
                                "lushuai_1986@163.com"))//邮箱
                        //License
                        .license("Apache 2.0")
                        //License 网址
                        .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0")
                        .build())

                // 支持的通讯协议集合
                .protocols(new LinkedHashSet<>(
                        Arrays.asList("https", "http")))

                // 授权信息设置,必要的header token等认证信息
                .securitySchemes(Collections.singletonList(
                        new ApiKey("BASE_TOKEN", "token", "pass")))

                // 授权信息全局应用
                .securityContexts(Collections.singletonList(
                                SecurityContext
                                        .builder()
                                        .securityReferences(Collections
                                                .singletonList(
                                                        new SecurityReference("BASE_TOKEN",
                                                                new AuthorizationScope[] {
                                                                        new AuthorizationScope("global", "")
                                                                }
                                                        )
                                                )
                                        )
                                        .build()
                        )
                );
    }
}

显示内容如下
在这里插入图片描述

五、Swagger 注解

@Api:用在请求的类上,表示对类的说明
    tags="说明该类的作用,可以在UI界面上看到的注解"
    value="该参数没什么意义,在UI界面上也看到,所以不需要配置"

@ApiOperation:用在请求的方法上,说明方法的用途、作用
    value="说明方法的用途、作用"
    notes="方法的备注说明"

@ApiParam:描述参数
	value="参数说明"
	required="boolean 是否必须"

@ApiImplicitParams:用在请求的方法上,表示一组参数说明
    @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
        name:参数名
        value:参数的汉字说明、解释
        required:参数是否必须传
        paramType:参数放在哪个地方
            · header --> 请求参数的获取:@RequestHeader
            · query --> 请求参数的获取:@RequestParam
            · path(用于restful接口)--> 请求参数的获取:@PathVariable
            · body(不常用)
            · form(不常用)    
        dataType:参数类型,默认String,其它值dataType="Integer"       
        defaultValue:参数的默认值

@ApiResponses:用在请求的方法上,表示一组响应
    @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
        code:数字,例如400
        message:信息,例如"请求参数没填好"
        response:抛出异常的类

@ApiModel:用于bean上,描述返回对象
    @ApiModelProperty:用在属性上,描述类的属性

@ApiIgnore:可以用在类、方法上,方法参数中,用来屏蔽某些接口或参数,使其不在页面上显示。
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

制作bug

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

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

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

打赏作者

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

抵扣说明:

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

余额充值