Spring Boot中如何使用Swagger详解

 更新时间:2021年08月06日 11:55:58   作者:团子大圆帅  
Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful风格的Web服务,这篇文章主要给大家介绍了关于Spring Boot中如何使用Swagger的相关资料,需要的朋友可以参考下

Swagger 简介

Swagger 是一个方便 API 开发的框架,它有以下优点:

  • 自动生成在线文档,后端开发人员的改动可以立即反映到在线文档,并且不用单独编写接口文档,减轻了开发负担
  • 支持通过 Swagger 页面直接调试接口,方便前端开发人员进行测试

配置 Swagger

Swagger 目前有 2.x 和 3.x 两个主流版本,配置略有不同。

添加依赖

首先去 Maven 仓库中搜索 springfox 查找依赖的坐标,Swagger 是遵循 OpenAPI 规范的技术,而 springfox 是该技术的一种实现,所以这里要搜 springfox 而不是 swagger。

对于 Swagger 2.x,需要在 pom.xml 中添加两项配置:

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<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>

对于 Swagger 3.x,简化了配置项,只需要在 pom.xml 中添加一项配置:

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-boot-starter -->
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-boot-starter</artifactId>
  <version>3.0.0</version>
</dependency>

为项目开启 Swagger

对于 Swagger 2.x,使用 @EnableSwagger2 注解开启 Swagger 功能。

@EnableSwagger2
@SpringBootApplication
public class SwaggerApplication {
    ...
}

对于 Swagger 3.x,使用 @EnableOpenApi 注解开启 Swagger 功能。

@EnableOpenApi
@SpringBootApplication
public class SwaggerApplication {
    ...
}

创建 SwaggerConfig 配置类

  • 对于 Swagger 2.x,实例化 Docket 的时候,需要传入 DocumentationType.SWAGGER_2。
  • 对于 Swagger 3.x,实例化 Docket 的时候,需要传入 DocumentationType.OAS_30。

下面是一份配置模板:

import org.springframework.beans.factory.annotation.Value;
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.spring.web.plugins.Docket;

@Configuration
public class SwaggerConfig {

    @Value("${spring.profiles.active:NA}")
    private String active;

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)  // OAS_30
                .enable("dev".equals(active))  // 仅在开发环境开启Swagger
                .apiInfo(apiInfo())
                .host("http://www.example.com")  // Base URL
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("API文档")
                .description("这是描述信息")
                .contact(new Contact("张三", null, null))
                .version("1.0")
                .build();
    }
}

访问 Swagger 前端页面

  • 对于 Swagger 2.x,访问 http://localhost:8080/swagger-ui.html
  • 对于 Swagger 3.x,访问 http://localhost:8080/swagger-ui/

控制器相关注解

@Api:将一个类标记为 Swagger 资源,一般放在 Controller 类上面,通过 tags 指定描述信息,比如 @Api(tags="用户管理")。

@ApiOperation:本注解放在 Controller 方法上面,描述该方法的作用。

@ApiParam:本注解放在 Controller 方法的形参前面,可以描述参数的作用,比如 @ApiParam("用户名") String username。可以使用 value 指定描述信息,通过 required = true 指定必需传递该参数。

package com.example.swagger.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "Hello控制器")
@RestController
public class HelloController {
    @ApiOperation("展示欢迎信息")
    @GetMapping("/hello")
    public String hello(@ApiParam("名字") String name) {
        return "hello, " + name;
    }
}

实体相关注解

  • @ApiModel:一般放在实体类上面。可以通过 value 指定别名,不指定时默认为类名。还可以通过 description 指定详细的描述信息。比如 @ApiModel("用户") 就将显示 用户 而不是 User。

![](cdn.jsdelivr.net/gh/jpch89/P… 在 Spring Boot 中使用 Swagger 00.png)
如果仅仅想指定描述,而不改变原始类名显示,可以写成 @ApiModel(description = "用户")。

  • @ApiModelProperty:一般放在实体类的成员变量上面,通过 value 指定描述信息,example 指定示例数据,required = true 指定该参数是必需的,hidden = true 用于隐藏该字段,不会在 API 文档中显示。
package com.example.swagger.pojo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
@ApiModel(description = "用户")
public class User {
    @ApiModelProperty("用户名")
    private String username;
    @ApiModelProperty("密码")
    private String password;
    @ApiModelProperty(value = "年龄", example = "18", required = true)
    private int age;
    @ApiModelProperty(hidden = true)
    private double money;
}

总结

到此这篇关于Spring Boot中如何使用Swagger的文章就介绍到这了,更多相关SpringBoot使用Swagger内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • maven-shade使用解决项目版本冲突

    maven-shade使用解决项目版本冲突

    在Maven项目中,第三方组件依赖可能与项目已有组件版本冲突,直接使用可能会导致项目运行失败,可以使用maven-shade-plugin插件,本文就来介绍一下maven-shade版本冲突,感兴趣的可以了解一下
    2024-10-10
  • Java中初始化List集合的6种方式详解

    Java中初始化List集合的6种方式详解

    这篇文章主要介绍了Java中初始化List集合的6种方式详解,List 是 Java 开发中经常会使用的集合,在使用List时需要进行初始化操作,今天我们就来看一下常用的几种list集合初始化方式,需要的朋友可以参考下
    2023-10-10
  • springBoot service层事务控制的操作

    springBoot service层事务控制的操作

    这篇文章主要介绍了springBoot service层事务控制的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • Java设计模式常用的七大原则总结

    Java设计模式常用的七大原则总结

    今天给大家总结了Java设计模式的七大原则,主要有单一职责原则,接口隔离原则,依赖倒转原则,里氏替换原则等,文中有非常详细的介绍,需要的朋友可以参考下
    2021-06-06
  • Java 十大排序算法之选择排序刨析

    Java 十大排序算法之选择排序刨析

    选择排序是一种简单直观的排序算法,无论什么数据进去都是 O(n&sup2;) 的时间复杂度。所以用到它的时候,数据规模越小越好。唯一的好处可能就是不占用额外的内存空间了吧
    2021-11-11
  • SpringBoot结合mybatis-plus实现分页的项目实践

    SpringBoot结合mybatis-plus实现分页的项目实践

    本文主要介绍了SpringBoot结合mybatis-plus实现分页的项目实践,主要基于MyBatis-Plus 自带的分页插件 PaginationInterceptor,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧
    2023-06-06
  • SpringDataElasticsearch与SpEL表达式实现ES动态索引

    SpringDataElasticsearch与SpEL表达式实现ES动态索引

    这篇文章主要介绍了SpringDataElasticsearch与SpEL表达式实现ES动态索引,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下
    2022-09-09
  • 基于FeignClient调用超时的处理方案

    基于FeignClient调用超时的处理方案

    这篇文章主要介绍了基于FeignClient调用超时的处理方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • 30分钟入门Java8之方法引用学习

    30分钟入门Java8之方法引用学习

    在Java8中,我们可以直接通过方法引用来简写lambda表达式中已经存在的方法,这篇文章主要介绍了30分钟入门Java8之方法引用学习,有兴趣可以了解一下。
    2017-04-04
  • Java基于命令模式实现邮局发信功能详解

    Java基于命令模式实现邮局发信功能详解

    这篇文章主要介绍了Java基于命令模式实现邮局发信功能,较为详细的分析了命令行模式的概念、原理并结合实例形式分析了Java使用命令行模式实现邮局发信功能的相关操作技巧与注意事项,需要的朋友可以参考下
    2018-04-04

最新评论