【Spring Boot 快速入门】五、Spring Boot集成Swagger UI

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群版 2核4GB 100GB
推荐场景:
搭建个人博客
云数据库 RDS MySQL,高可用版 2核4GB 50GB
简介: 【Spring Boot 快速入门】五、Spring Boot集成Swagger UI

前言


  相信大部分的开发人员都或多或少地被接口文档折磨过。后端人员接口开发完成,又需编写及维护接口文档会耗费不少精力,经常来不及更新。Swagger基于注解进行开发,提供了一个灵活的接口文档模板。更新运行编译后,直接可以在线预览,避免了重复修改的问题,下面开始介绍Swagger UI。


什么是Swagger UI


  Swagger UI是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。主要作用是:接口的文档在线自动生成和在线预览,可以进行业务功能的测试。

  目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法、参数和模型紧密集成到服务器端的代码,允许 API 来始终保持同步。Swagger 让部署管理和使用功能强大的 API 从未如此简单。


Swagger UI的使用


引入依赖


  Maven方式引入所需要的依赖包,具体信息如下:


<!-- swagger start -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.5.0</version>
        </dependency>
        <!-- swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.5.0</version>
        </dependency>
        <!-- swagger end -->


Swagger UI 配置类


  Swagger UI 配置类首先是提供了一个强大的构造器,用于创建API。其中构建API的基本信息有页面的标题、版本号、接口文档的描述、服务条款的地址、contact、许可信息、许可信息地址等,其中contact里面可以其他更多的信息。

  • ApiInfo:构建Api文档的详细信息函数。
  • Docket:Swagger UI返回的API文档信息。

  其中主要属性有:

  • apiInfo()是apiInfo的基本信息。
  • select()Api 选择器生成器。
  • apis为当前请求处理程序选择器所需要进行API文档的包路径。
  • paths路径选择器为any任何包都处理。


public class SwaggerConfig {
   @Bean
   public Docket createRestApi() {
       return new Docket(DocumentationType.SWAGGER_2)
               .apiInfo(apiInfo())
               .select()
               //为当前包路径
               .apis(RequestHandlerSelectors.basePackage("com.example.demo"))
               .paths(PathSelectors.any())
               .build();
   }
   private ApiInfo apiInfo() {
       return new ApiInfoBuilder()
               .title("Spring Boot 使用 Swagger2 构建RESTful API")
               .contact(new Contact("Bryan", "http://blog.bianxh.top/", ""))
               .version("1.0")
               .description("API 描述")
               .build();
   }


Swagger UI 注解


  • @Api:用在类上,说明该类的作用。
  • @ApiOperation:注解来给API增加方法说明。
  • @ApiImplicitParams : 用在方法上包含一组参数说明。
  • @ApiImplicitParam:用来注解来给方法入参增加说明。

常用的参数:


paramType:指定参数放在哪个地方
    header:请求参数放置于Request Header,使用@RequestHeader获取
    query:请求参数放置于请求地址,使用@RequestParam获取
    path:(用于restful接口)-->请求参数的获取:@PathVariable
    body:(不常用)
    form(不常用)
    name:参数名
    dataType:参数类型
    required:参数是否必须传(true | false)
    value:说明参数的意思
    defaultValue:参数的默认值
  • @ApiResponses:用于表示一组响应
  • @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息。 其中ApiResponse包含三个属性


code:数字,例如200 请求成功
    message:信息,例如"请求成功"
    response:请求成功返回的数据信息


@ApiModel:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)

@ApiModelProperty:描述一个model的属性


源码


pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>swagger</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>swagger</name>
    <description>Demo project for Spring Boot and MyBatis and Swagger</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!-- commons start -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.7</version>
        </dependency>
        <!-- commons end -->
        <!-- mybatis start-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <!-- druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.11</version>
        </dependency>
        <!-- mybatis end-->
        <!--junit start -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- junjit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!--junit  end -->
        <!-- swagger start -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.5.0</version>
        </dependency>
        <!-- swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.5.0</version>
        </dependency>
        <!-- swagger end -->
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>


application.properties


server.port=8888
# mysql
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
spring.datasource.username=test
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
mybatis.mapper-locations=classpath*:mapper/**/*.xml


SwaggerConfig


package com.example.demo.config;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
 * @ClassName SwaggerConfig
 * @Description: SwaggerConfig配置
 * @Author JavaZhan @公众号:Java全栈架构师
 * @Date 2020/6/13
 * @Version V1.0
 **/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    /**
    * @ClassName 创建Docket
    * @Description: 创建Docket
    * @Author JavaZhan @公众号:Java全栈架构师
    * @Date 2020/6/13
    * @Version V1.0
    **/
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo"))
                .paths(PathSelectors.any())
                .build();
    }
    /**
     * @ClassName ApiInfo
     * @Description: ApiInfo
     * @Author JavaZhan @公众号:Java全栈架构师
     * @Date 2020/6/13
     * @Version V1.0
     **/
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("掘金作者 小阿杰")
                .contact(new Contact("小阿杰","https://juejin.cn/user/2040300414187416/posts", ""))
                .version("1.0")
                .description("公众号: Java全栈架构师 API 描述")
                .build();
    }
}


DemoSwaggerApplication


package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * @ClassName Swagger UI集成测试
 * @Description: Swagger UI集成测试启动类
 * @Author JavaZhan @公众号:Java全栈架构师
 * @Date 2020/6/13
 * @Version V1.0
 **/
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoSwaggerApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoSwaggerApplication.class, args);
    }
}
复制代码

UserController

package com.example.demo.controller;
import com.example.demo.module.User;
import com.example.demo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.List;
/**
 * @ClassName UserController
 * @Description: 用户管理
 * @Author JavaZhan @公众号:Java全栈架构师
 * @Date 2020/6/13
 * @Version V1.0
 **/
@Api(description = "用户管理")
@RequestMapping("user")
@Controller
public class UserController {
    @Resource
    private UserService userService;
    @ApiOperation(value = "获取所有用户")
    @RequestMapping(value = "getAllUser",method = RequestMethod.GET)
    @ResponseBody
    public List<User> getAllUser(){
        return userService.getAllUser();
    }
}


使用Swagger UI


打开API


  在浏览器输入:http://localhost:8888/swagger-ui.html出现如下图中接口文档信息,即Swagger文档集成成功:


image.png


测试接口


  选择user/getAllUser这个接口,获取所有用户信息, 可以看到请求方式是GET请求。请求参数为空,返回的Model是User,image.png

点击Try it out 。接口自动请求,返回请求参数和返回的值信息。请求成功,返回状态为200。返回正常的List数据信息。


image.png


结语


  这样Swagger与Spring Boot集成成功啦。更多的测试大家可以深入研究一下Swagger相关信息,相信一定会有新大陆发现的。



相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
13天前
|
缓存 NoSQL Java
SpringBoot的三种缓存技术(Spring Cache、Layering Cache 框架、Alibaba JetCache 框架)
Spring Cache 是 Spring 提供的简易缓存方案,支持本地与 Redis 缓存。通过添加 `spring-boot-starter-data-redis` 和 `spring-boot-starter-cache` 依赖,并使用 `@EnableCaching` 开启缓存功能。JetCache 由阿里开源,功能更丰富,支持多级缓存和异步 API,通过引入 `jetcache-starter-redis` 依赖并配置 YAML 文件启用。Layering Cache 则提供分层缓存机制,需引入 `layering-cache-starter` 依赖并使用特定注解实现缓存逻辑。
SpringBoot的三种缓存技术(Spring Cache、Layering Cache 框架、Alibaba JetCache 框架)
|
1天前
|
Java 微服务 Spring
SpringBoot+Vue+Spring Cloud Alibaba 实现大型电商系统【分布式微服务实现】
文章介绍了如何利用Spring Cloud Alibaba快速构建大型电商系统的分布式微服务,包括服务限流降级等主要功能的实现,并通过注解和配置简化了Spring Cloud应用的接入和搭建过程。
SpringBoot+Vue+Spring Cloud Alibaba 实现大型电商系统【分布式微服务实现】
|
5天前
|
Java API Spring
springboot集成swagger
这篇文章介绍了如何在Spring Boot项目中集成Swagger 2.10.0来生成API文档,包括添加依赖、编写配置类、创建接口文档,并使用Knife4j美化Swagger界面。
|
5天前
|
安全 Java 数据安全/隐私保护
基于SpringBoot+Spring Security+Jpa的校园图书管理系统
本文介绍了一个基于SpringBoot、Spring Security和JPA开发的校园图书管理系统,包括系统的核心控制器`LoginController`的代码实现,该控制器处理用户登录、注销、密码更新、角色管理等功能,并提供了系统初始化测试数据的方法。
10 0
基于SpringBoot+Spring Security+Jpa的校园图书管理系统
|
7天前
|
安全 Java 数据库
|
7天前
|
JSON 安全 Java
|
14天前
|
消息中间件 安全 Java
Spring Boot 基于 SCRAM 认证集成 Kafka 的详解
【8月更文挑战第4天】本文详解Spring Boot结合SCRAM认证集成Kafka的过程。SCRAM为Kafka提供安全身份验证。首先确认Kafka服务已启用SCRAM,并准备认证凭据。接着,在`pom.xml`添加`spring-kafka`依赖,并在`application.properties`中配置Kafka属性,包括SASL_SSL协议与SCRAM-SHA-256机制。创建生产者与消费者类以实现消息的发送与接收功能。最后,通过实际消息传递测试集成效果与认证机制的有效性。
|
8天前
|
Java
SpringBoot 配置 Swagger
SpringBoot 配置 Swagger
15 0
|
3月前
|
前端开发 搜索推荐 开发者
SAP UI5 sap.m.Column 控件的 minScreenWidth 属性介绍
SAP UI5 sap.m.Column 控件的 minScreenWidth 属性介绍
|
3月前
|
JavaScript 前端开发 开发者
SAP UI5 控件 sap.m.ListBase 的 inset 属性的作用介绍
SAP UI5 控件 sap.m.ListBase 的 inset 属性的作用介绍