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

本文涉及的产品
RDS MySQL DuckDB 分析主实例,基础系列 4核8GB
RDS DuckDB + QuickBI 企业套餐,8核32GB + QuickBI 专业版
RDS MySQL DuckDB 分析主实例,集群系列 4核8GB
简介: 【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相关信息,相信一定会有新大陆发现的。



相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
7月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
719 2
|
8月前
|
人工智能 Java 机器人
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
Spring AI Alibaba集成Ollama,基于Java构建本地大模型应用,支持流式对话、knife4j接口可视化,实现高隐私、免API密钥的离线AI服务。
6817 2
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
存储 JSON Java
895 0
|
9月前
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
1365 3
|
JSON 监控 JavaScript
Swagger UI 本地主机教程: 如何在本地使用 Swagger UI?
Swagger UI 提供在线和离线版本,但由于各种原因,你可能需要在本地使用 Swagger UI。 在本文中,我们将向你展示如何在本地使用 Swagger UI。
|
安全 Java Apache
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 身份和权限认证
本文介绍了 Apache Shiro 的身份认证与权限认证机制。在身份认证部分,分析了 Shiro 的认证流程,包括应用程序调用 `Subject.login(token)` 方法、SecurityManager 接管认证以及通过 Realm 进行具体的安全验证。权限认证部分阐述了权限(permission)、角色(role)和用户(user)三者的关系,其中用户可拥有多个角色,角色则对应不同的权限组合,例如普通用户仅能查看或添加信息,而管理员可执行所有操作。
644 0
|
Java 数据库连接 数据库
|
7月前
|
Java 测试技术 数据库连接
【SpringBoot(四)】还不懂文件上传?JUnit使用?本文带你了解SpringBoot的文件上传、异常处理、组件注入等知识!并且带你领悟JUnit单元测试的使用!
Spring专栏第四章,本文带你上手 SpringBoot 的文件上传、异常处理、组件注入等功能 并且为你演示Junit5的基础上手体验
1115 3