Swagger

Swagger

  • 号称世界上最流行的API框架
  • Restful Api 文档在线自动生成器 => API 文档 与API 定义同步更新
  • 直接运行,在线测试API
  • 支持多种语言 (如:Java,PHP等)

1. SpringBoot集成Swagger

  1. 创建springboot工程、引入web模块、编写一个hello world页面
  2. 引入依赖jar包:
    • swagger2
    • ui

maven官网搜索:springfox swagger 找到swagger2和ui依赖引入:

<!--swagger 2-->
         <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

整合knife4j总依赖

 <!--swagger knife4j-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>2.0.4</version>
        </dependency>
        <!--springfox-swagger-ui -->
        <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
        <!--指定swagger-models版本,解决报错-->
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.21</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>1.5.21</version>
        </dependency>
  1. config中配置swagger2:
@Configuration
@EnableSwagger2 //开启swagger2
public class SwaggerConfig {

}

  1. 运行测试;
http://localhost:8080/swagger-ui.html

在这里插入图片描述

2.配置swagger的api信息

//配置Swagger的Docket的bean实例
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo());//配置Swagger信息
    }
    //配置Swagger信息
    private ApiInfo apiInfo() {
        return new ApiInfo(
                "钟情",           //标题
                "一往无前,远方",  //描述
                "v1.0",          //版本
                "https://blog.youkuaiyun.com/sentence5",   //组织链接
                new Contact("钟情", "https://blog.youkuaiyun.com/sentence5", "gz_qing@qq.com"),//作者信息
                "Apache 2.0",     //许可
                "http://www.apache.org/licenses/LICENSE-2.0",  //许可链接
                new ArrayList<VendorExtension>());  //扩展
    }

在这里插入图片描述

3.扫描接口

 //配置Swagger的Docket的bean实例
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())//配置Swagger信息
        //是否启动swagger 如果是false则不能在浏览器中使用
                .enable(true)
                .select()
                //RequestHandlerSelectors. 配置要扫描的方式
                //basePackage():指定要扫描的包
                //any():扫描全部
                //none():不扫描
                //withClassAnnotation():扫描类上的注解,参数是一个注解的反射对象
                //withMethodAnnotation():扫描方法上的注解
                .apis(RequestHandlerSelectors.basePackage("com.qing.swagger.controller"))
                //.paths() .过滤URL
                //any() 任何请求都扫描
                //none() 任何请求都不扫描
                //ant()	通过ant控制
                //regex() 通过正则表达式控制
                .paths(PathSelectors.ant("/qing/**")) //表示不扫描这里面的内容
                .build();
    }

4.配置swagger开关

  1. 我只希望我在生产环境中使用,在正式环境不使用
  • 判断是不是生产环境 flag=false
  • 注入enable();
  1. 新增两个配置文件:
    在这里插入图片描述
    指定开发环境:#spring.profiles.active=dev
@Configuration
@EnableSwagger2 //开启swagger2
public class SwaggerConfig {

    //配置Swagger的Docket的bean实例
    @Bean
    public Docket docket(Environment environment){

        //设置要显示的swagger环境, 如果是dev环境就启动测试
        Profiles profiles = Profiles.of("dev", "test");
        //通过environment.acceptsProfiles判断是否处于自己设定的环境中
        boolean flag = environment.acceptsProfiles(profiles);
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(flag)
                .select()
                //配置要扫描的接口
                .apis(RequestHandlerSelectors.basePackage("com.qing.swagger.controller"))
                //.paths(PathSelectors.ant("/qing/**"))
                .build();
    }

    //配置Swagger信息
    private ApiInfo apiInfo() {
        return new ApiInfo(
                "钟情",           //标题
                "一往无前,远方",  //描述
                "v1.0",          //版本
                "https://blog.youkuaiyun.com/sentence5",   //组织链接
                new Contact("钟情", "https://blog.youkuaiyun.com/sentence5", "gz_qing@qq.com"),//作者信息
                "Apache 2.0",     //许可
                "http://www.apache.org/licenses/LICENSE-2.0",  //许可链接
                new ArrayList<VendorExtension>());  //扩展
    }
}


5.配置api文档分组

  1. 创建一个分组(一个dockert一个分组):.groupName("钟情")在这里插入图片描述
  2. 创建多个分组
     //创建多个分组
    @Bean
    public Docket docket1(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("A");
    }
    @Bean
    public Docket docket2(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("B");
    }
  1. 注释
注释含义
@Api(tags ="")controller总接口注释
@ApiOperation("")单个接口注释
@ApiParam("")用户名参数注释
@ApiModel("")实体类注释
@ApiModelProperty("")实体参数注释
  • 实体类注释:
@ApiModel("用户实体类") //类注释
public class User {
    @ApiModelProperty("用户名")  //字段注释
    public String username;
    @ApiModelProperty("密码")
    public String password;
}

-

  • 接口注释
@Api(tags ="用户相关接口")  //控制类总接口提示
@RestController
public class MyController {

    @GetMapping ("/hello")
    public String hello(){
        return "hello world";
    }

    @ApiOperation("返回对象接口") //单个接口提示
    @PostMapping("/user")
    public User user(){
        return new User();
    }
    @ApiOperation("返回用户名接口")
    @GetMapping("/hello2")
    public String user(@ApiParam("用户名参数") String username){
        return "hello"+username;
    }

}

在这里插入图片描述

swagger的增强UI -knife4j(转载https://blog.youkuaiyun.com/weixin_47083537/article/details/107484915)

knife4j简介

knife4j是springfox-swagger的增强UI实现,为Java开发者在使用Swagger的时候,提供了简洁、强大的接口文档体验。knife4j完全遵循了springfox-swagger中的使用方式,并在此基础上做了增强功能,如果你用过Swagger,你就可以无缝切换到knife4j。

使用方式:

  1. 添加相关依赖:
        <!--指定swagger-models版本,解决报错-->
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.21</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>1.5.21</version>
        </dependency>
<!--整合Knife4j-->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>2.0.4</version>
</dependency>
  1. 在config包下添加配置类
/**
 * Swagger2API文档的配置
 */
@Configuration
@EnableSwagger2
@EnableKnife4j   //开启knife4j的增强功能
public class Swagger2Config {
    
}
  1. 运行我们的SpringBoot应用,访问API文档地址即可查看:http://localhost:8080/doc.html
    在这里插入图片描述
<think>好的,我现在需要处理用户关于Swagger API文档工具的使用指南的请求。首先,用户明确提到想了解Swagger或查找相关技术资料,特别是使用指南。根据用户提供的系统级指令,我需要确保回答结构清晰,使用中文,正确应用LaTeX格式,并生成相关问题。同时,用户的历史引用中有两篇关于Swagger的文章,我需要参考这些内容,但也要注意用户指出这些引用并非真实需求,可能需要更多依赖之前的互动,不过当前对话中用户只提到了这两篇,所以得合理利用。 首先,我应该先确定用户的需求层次。他们可能希望了解Swagger的基本概念、如何安装配置、如何编写API文档以及相关工具的使用,比如生成离线文档。根据引用[1],Swagger用于创建和管理RESTful API文档,提供交互式测试界面。引用[2]提到一个离线工具,可以转换在线文档为HTML或Markdown。因此,在回答中需要涵盖基础使用步骤,并可能提到离线工具作为扩展内容。 接下来,我需要按照用户的要求分步骤说明,结构清晰。可能需要分为以下几个部分:1. Swagger简介;2. 安装与配置;3. 编写API文档;4. 生成离线文档。每个部分需要简明扼要,同时嵌入引用标记。例如,在介绍Swagger时引用[^1],在离线工具部分引用[^2]。 另外,需要注意LaTeX格式的应用。比如,变量或技术术语如YAML文件是否需要使用行内数学表达式?可能不需要,但如果有示例代码中的路径或文件名,可能需要用代码块而非LaTeX。用户要求行内数学表达式用$...$,但技术文档中的代码部分应使用代码块,如示例中的Python代码。因此,在回答中,我会正确使用代码块和LaTeX,比如在提到数学公式时使用,但可能在这个主题下数学公式较少,更多是代码示例。 生成相关问题部分,需要考虑用户可能进一步询问的内容,比如Swagger UI的定制、安全配置、与其他工具的对比、离线文档工具的具体使用步骤等。需要确保问题覆盖用户可能感兴趣的扩展话题。 最后,检查是否符合所有系统指令:中文回答、正确格式、引用标识自然、相关问题生成。需要确保没有使用Markdown格式,除了代码块,但用户示例中的代码块使用了```python,所以可能允许。同时,回答中的引用标识应放在相关段落末尾,如[^1]和[^2]。</think>### Swagger API 文档工具使用指南 #### 1. Swagger 简介 Swagger(现称为 OpenAPI 规范)是一套用于设计、构建和记录 RESTful API 的开源工具集。它通过标准化的 YAML/JSON 格式描述 API 结构,并提供交互式界面$^{[^1]}$。核心功能包括: - **API 设计**:使用 `swagger.yaml` 或 `swagger.json` 定义接口 - **文档生成**:自动生成可读性强的 HTML 页面 - **接口测试**:直接在浏览器中模拟 API 调用 #### 2. 安装与配置 以 Node.js 环境为例: ```bash # 安装 Swagger 命令行工具 npm install -g swagger # 初始化项目 swagger project create my-api ``` 配置文件 `config/default.yaml` 中可设置服务器端口、数据库连接等参数$^{[^1]}$。 #### 3. 编写 API 文档 创建 `api/swagger/swagger.yaml` 文件: ```yaml swagger: "2.0" info: title: 用户管理系统 version: 1.0.0 paths: /users: get: summary: 获取用户列表 responses: 200: description: 成功返回用户列表 ``` #### 4. 生成离线文档 使用 SwaggerOfflineDoc 工具转换在线文档为离线格式$^{[^2]}$: ```bash # 下载工具 git clone https://github.com/example/SwaggerOfflineDoc # 生成 HTML 文档 python convert.py --input http://api.example.com/swagger.json --format html ``` #### 5. 高级功能 - **安全定义**:添加 OAuth2/JWT 认证 ```yaml securityDefinitions: Bearer: type: apiKey name: Authorization in: header ``` - **数据模型**:定义可复用的数据结构 ```yaml definitions: User: type: object properties: id: type: integer name: type: string ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值