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

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
简介: 【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相关信息,相信一定会有新大陆发现的。



相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
打赏
0
0
0
0
7
分享
相关文章
Spring 集成 DeepSeek 的 3大方法(史上最全)
DeepSeek 的 API 接口和 OpenAI 是兼容的。我们可以自定义 http client,按照 OpenAI 的rest 接口格式,去访问 DeepSeek。自定义 Client 集成DeepSeek ,可以通过以下步骤实现。步骤 1:准备工作访问 DeepSeek 的开发者平台,注册并获取 API 密钥。DeepSeek 提供了与 OpenAI 兼容的 API 端点(例如),确保你已获取正确的 API 地址。
Spring 集成 DeepSeek 的 3大方法(史上最全)
支持 40+ 插件,Spring AI Alibaba 简化智能体私有数据集成
通过使用社区官方提供的超过 20 种 RAG 数据源和 20 种 Tool Calling 接口,开发者可以轻松接入多种外部数据源(如 GitHub、飞书、云 OSS 等)以及调用各种工具(如天气预报、地图导航、翻译服务等)。这些默认实现大大简化了智能体的开发过程,使得开发者无需从零开始,便可以快速构建功能强大的智能体系统。通过这种方式,智能体不仅能够高效处理复杂任务,还能适应各种应用场景,提供更加智能、精准的服务。
|
2月前
|
使用Spring Boot集成Nacos
通过上述步骤,Spring Boot应用可以成功集成Nacos,利用Nacos的服务发现和配置管理功能来提升微服务架构的灵活性和可维护性。通过这种集成,开发者可以更高效地管理和部署微服务。
317 17
Spring AI 智能体通过 MCP 集成本地文件数据
MCP 作为一款开放协议,直接规范了应用程序如何向 LLM 提供上下文。MCP 就像是面向 AI 应用程序的 USB-C 端口,正如 USB-C 提供了一种将设备连接到各种外围设备和配件的标准化方式一样,MCP 提供了一个将 AI 模型连接到不同数据源和工具的标准化方法。
616 14
Spring Boot 3 集成 Spring Security + JWT
本文详细介绍了如何使用Spring Boot 3和Spring Security集成JWT,实现前后端分离的安全认证概述了从入门到引入数据库,再到使用JWT的完整流程。列举了项目中用到的关键依赖,如MyBatis-Plus、Hutool等。简要提及了系统配置表、部门表、字典表等表结构。使用Hutool-jwt工具类进行JWT校验。配置忽略路径、禁用CSRF、添加JWT校验过滤器等。实现登录接口,返回token等信息。
634 12
Spring Boot 3 集成Spring AOP实现系统日志记录
本文介绍了如何在Spring Boot 3中集成Spring AOP实现系统日志记录功能。通过定义`SysLog`注解和配置相应的AOP切面,可以在方法执行前后自动记录日志信息,包括操作的开始时间、结束时间、请求参数、返回结果、异常信息等,并将这些信息保存到数据库中。此外,还使用了`ThreadLocal`变量来存储每个线程独立的日志数据,确保线程安全。文中还展示了项目实战中的部分代码片段,以及基于Spring Boot 3 + Vue 3构建的快速开发框架的简介与内置功能列表。此框架结合了当前主流技术栈,提供了用户管理、权限控制、接口文档自动生成等多项实用特性。
99 8
SpringBoot整合Flowable【03】- 通过Flowable-UI体验一个简单流程
本文介绍了如何使用Flowable 7.0以下版本的flowable-ui进行流程建模、发布和执行。首先,通过解压并启动flowable-ui war包,访问http://localhost:8080/flowable-ui/idm/#/login登录系统。接着,创建并绘制一个简单的绩效流程模型,包含开始节点、任务节点(自评、上级评、隔级评)和结束节点,并为各节点分配处理人。然后,创建应用并发布绩效流程。最后,通过创建a、b、c三个用户分别完成各节点任务,演示了整个流程的执行过程。本文旨在帮助读者理解Flowable的基本操作和流程元素,后续将介绍通过Java代码控制流程的方法。
183 0
SpringBoot整合Flowable【03】- 通过Flowable-UI体验一个简单流程
|
3月前
|
Spring Boot集成MinIO
本文介绍了如何在Spring Boot项目中集成MinIO,一个高性能的分布式对象存储服务。主要步骤包括:引入MinIO依赖、配置MinIO属性、创建MinIO配置类和服务类、使用服务类实现文件上传和下载功能,以及运行应用进行测试。通过这些步骤,可以轻松地在项目中使用MinIO的对象存储功能。
197 5
什么是Apache Kafka?如何将其与Spring Boot集成?
什么是Apache Kafka?如何将其与Spring Boot集成?
136 5
Spring Boot 与 Apache Kafka 集成详解:构建高效消息驱动应用
Spring Boot 与 Apache Kafka 集成详解:构建高效消息驱动应用
102 1

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等