SpringBoot【3】集成 Swagger

2024-06-22 13:28

本文主要是介绍SpringBoot【3】集成 Swagger,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

SpringBoot 集成 Swagger

  • 前言
  • pom.xml 配置文件
  • application.yml 配置文件
  • config 包
    • Swagger2Config
  • entity 包
    • UserEntity
  • service 包
    • impl 包
      • SwaggerServiceImpl
    • SwaggerService
  • controller 包
    • SwaggerController
  • SwaggerApplication
  • 验证

前言

创建项目步骤、及版本选择等,在《SpringBoot【1】集成 Druid》章节中有详细介绍,此处不再重复概述。

当前先说明下,为什么需要集成 Swagger ??

  • 如下一个控制层(Controller)代码:
  • 在这里插入图片描述

若不集成 Swagger,则 在页面进行测试时,将是如下这样:
在这里插入图片描述
每次调用测试,都需要在浏览器访问。
测试多个方法时、甚是繁琐。
于是乎, 你就开始了“奇思幻想”:有没有一种办法可以不这么繁琐,而又能测试?

  • 答案呢,肯定是有的。比如呢? 集成 junit 写单元测试、或者浏览器安装插件等等。此处:我们集成Swagger 来解决此问题,注意 此处的版本是 Swagger2 (第2代)

集成之后,在进行测试,是长这样子的:
在这里插入图片描述

SpringBoot 集成 Swagger2 完成之后,项目截图如下 :

在这里插入图片描述

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 http://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.12.RELEASE</version><relativePath /></parent><groupId>com.junjiu.springboot.swagger</groupId><artifactId>junjiu-springboot-swagger</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--以下 3个依赖是集成 Swagger2 所需--><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>3.0.0</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>3.0.0</version></dependency><dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId><version>3.0.3</version></dependency><!--UserEntity 中为了使用 @data 注解,当前添加 lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies></project>

application.yml 配置文件


server:port: 5826spring:application:name: Junjiu-Springboot-Swaggerversion: 1.0.0

config 包

Swagger2Config

package com.junjiu.springboot.swagger.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;/*** program: junjiu-springboot-swagger* ClassName: Swagger2Config* description:** @author: 九尊* @create: 2024-06-20 23:00* @version: 1.0**/
@EnableSwagger2
@Configuration
public class Swagger2Config {@Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.junjiu.springboot.swagger")).paths(PathSelectors.any()).build();}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("Swagger2").description("SpringBoot 集成 Swagger2").contact(new Contact("君九", "https://blog.csdn.net/charlesyuangc", "123456@email.com")).termsOfServiceUrl("https://blog.csdn.net/charlesyuangc").version("version 1.0").build();}}

entity 包

UserEntity

package com.junjiu.springboot.swagger.entity;import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;/*** program: junjiu-springboot-swagger* ClassName: UserEntity* description: 实体类. 对接 数据库中的表,例如:tb_user,*              此处为了演示 Swagger2 在实体类中的注解使用,暂不再创建表了。** @author: 九尊* @create: 2024-06-20 23:07* @version: 1.0**/
@Data
@ApiModel(value = "用户实体类", description = "用户实体类")
public class UserEntity {/*** 以下 3种 写法均可以的。*/// @ApiModelProperty(value = "用户ID", name = "id", required = true)// @ApiModelProperty(value = "用户ID", name = "id")@ApiModelProperty(value = "用户ID")private Long id;@ApiModelProperty(value = "用户名", name = "userName")private String userName;@ApiModelProperty(value = "昵称", name = "nickName", required = true)private String nickName;}

service 包

impl 包

SwaggerServiceImpl

package com.junjiu.springboot.swagger.service.impl;import com.junjiu.springboot.swagger.entity.UserEntity;
import com.junjiu.springboot.swagger.service.SwaggerService;
import org.springframework.stereotype.Service;/*** program: junjiu-springboot-swagger* ClassName: SwaggerServiceImpl* description:** @author: 九尊* @create: 2024-06-20 22:47* @version: 1.0**/
@Service
public class SwaggerServiceImpl implements SwaggerService {@Overridepublic String setAdd(Integer numA, Integer numB) {Integer total = numA + numB;return "运行结果是:" + String.valueOf(total);}@Overridepublic UserEntity getUser(Long id) {System.out.println("id:" + id);// 从数据库中查询到数据后,返回对象。UserEntity userEntity = new UserEntity();userEntity.setId(id);userEntity.setUserName("君九");userEntity.setNickName("九皇叔叔");return userEntity;}@Overridepublic String setUpdate(UserEntity userEntity) {return "用户信息更新成功.";}
}

SwaggerService

package com.junjiu.springboot.swagger.service;import com.junjiu.springboot.swagger.entity.UserEntity;/*** program: junjiu-springboot-swagger* ClassName: SwaggerService* description:** @author: 九尊* @create: 2024-06-20 22:46* @version: 1.0**/
public interface SwaggerService {/*** 测试接口 | 加法运算.* @param numA* @param numB* @return*/String setAdd(Integer numA, Integer numB);/*** 根据用户ID编号查询用户信息.* @param id* @return*/UserEntity getUser(Long id);/*** 更新用户信息.* @param userEntity* @return*/String setUpdate(UserEntity userEntity);
}

controller 包

SwaggerController

package com.junjiu.springboot.swagger.controller;import com.junjiu.springboot.swagger.entity.UserEntity;
import com.junjiu.springboot.swagger.service.SwaggerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;/*** program: junjiu-springboot-swagger* ClassName: SwaggerController* description:** @author: 九尊* @create: 2024-06-20 22:46* @version: 1.0**/
@Api(value = "Swagger 示例", tags = "Swagger 示例 Api")
@RestController
public class SwaggerController {@Autowiredprivate SwaggerService swaggerService;/*** 测试方法 | 加法运算,需要注意此处有 2个参数* @param numA* @param numB* @return*/@ApiOperation("加法运算方法.")@ApiImplicitParams({@ApiImplicitParam(name = "numA", value = "第一个参数", required = true, dataType = "Integer", paramType = "path", example = "10"),@ApiImplicitParam(name = "numB", value = "第二个参数", required = true, dataType = "Integer", paramType = "path", example = "20")})@GetMapping("/setAdd/{numA}/{numB}")public String setAdd(@PathVariable("numA") Integer numA,@PathVariable("numB") Integer numB) {return swaggerService.setAdd(numA, numB);}/*** 测试方法 | 根据 id编号 查询用户信息,注意:这里只有 1个参数.* @param id* @return*/@ApiOperation("获取用户信息")@ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Long", paramType = "path", example = "1")@GetMapping("/getUser/{id}")public UserEntity getUser(@PathVariable("id") Long id){return swaggerService.getUser(id);}/*** 更新用户信息 .* @param userEntity* @return*/@ApiOperation("更新用户信息")@ApiImplicitParam(name = "userEntity", value = "用户实体类", required = true, dataType = "UserEntity", paramType = "body")@PutMapping("/setUpdate")public String setUpdate(UserEntity userEntity) {return swaggerService.setUpdate(userEntity);}}

SwaggerApplication

package com.junjiu.springboot.swagger;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;/*** program: junjiu-springboot-swagger* ClassName: SwaggerApplication* description:** @author: 九尊* @create: 2024-06-20 22:45* @version: 1.0**/
@SpringBootApplication
public class SwaggerApplication {public static void main(String[] args) {SpringApplication.run(SwaggerApplication.class, args);}
}

验证

启动之后,
在这里插入图片描述

在浏览器地址栏访问:
http://localhost:5826/doc.html
在这里插入图片描述

示例说明
获取用户信息 API 为例:
在这里插入图片描述
在这里插入图片描述

这篇关于SpringBoot【3】集成 Swagger的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1084415

相关文章

Spring Boot配置和使用两个数据源的实现步骤

《SpringBoot配置和使用两个数据源的实现步骤》本文详解SpringBoot配置双数据源方法,包含配置文件设置、Bean创建、事务管理器配置及@Qualifier注解使用,强调主数据源标记、代... 目录Spring Boot配置和使用两个数据源技术背景实现步骤1. 配置数据源信息2. 创建数据源Be

Spring Boot 3.x 中 WebClient 示例详解析

《SpringBoot3.x中WebClient示例详解析》SpringBoot3.x中WebClient是响应式HTTP客户端,替代RestTemplate,支持异步非阻塞请求,涵盖GET... 目录Spring Boot 3.x 中 WebClient 全面详解及示例1. WebClient 简介2.

Java中使用 @Builder 注解的简单示例

《Java中使用@Builder注解的简单示例》@Builder简化构建但存在复杂性,需配合其他注解,导致可变性、抽象类型处理难题,链式编程非最佳实践,适合长期对象,避免与@Data混用,改用@G... 目录一、案例二、不足之处大多数同学使用 @Builder 无非就是为了链式编程,然而 @Builder

在IntelliJ IDEA中高效运行与调试Spring Boot项目的实战步骤

《在IntelliJIDEA中高效运行与调试SpringBoot项目的实战步骤》本章详解SpringBoot项目导入IntelliJIDEA的流程,教授运行与调试技巧,包括断点设置与变量查看,奠定... 目录引言:为良驹配上好鞍一、为何选择IntelliJ IDEA?二、实战:导入并运行你的第一个项目步骤1

Spring Boot从main方法到内嵌Tomcat的全过程(自动化流程)

《SpringBoot从main方法到内嵌Tomcat的全过程(自动化流程)》SpringBoot启动始于main方法,创建SpringApplication实例,初始化上下文,准备环境,刷新容器并... 目录1. 入口:main方法2. SpringApplication初始化2.1 构造阶段3. 运行阶

Spring Boot3.0新特性全面解析与应用实战

《SpringBoot3.0新特性全面解析与应用实战》SpringBoot3.0作为Spring生态系统的一个重要里程碑,带来了众多令人兴奋的新特性和改进,本文将深入解析SpringBoot3.0的... 目录核心变化概览Java版本要求提升迁移至Jakarta EE重要新特性详解1. Native Ima

Java中的xxl-job调度器线程池工作机制

《Java中的xxl-job调度器线程池工作机制》xxl-job通过快慢线程池分离短时与长时任务,动态降级超时任务至慢池,结合异步触发和资源隔离机制,提升高频调度的性能与稳定性,支撑高并发场景下的可靠... 目录⚙️ 一、调度器线程池的核心设计 二、线程池的工作流程 三、线程池配置参数与优化 四、总结:线程

Spring Boot 与微服务入门实战详细总结

《SpringBoot与微服务入门实战详细总结》本文讲解SpringBoot框架的核心特性如快速构建、自动配置、零XML与微服务架构的定义、演进及优缺点,涵盖开发环境准备和HelloWorld实战... 目录一、Spring Boot 核心概述二、微服务架构详解1. 微服务的定义与演进2. 微服务的优缺点三

我们来说说Java LockSupport 的 park 和 unpark

《我们来说说JavaLockSupport的park和unpark》LockSupport是JDK底层线程阻塞工具,通过park/unpark实现线程阻塞与唤醒,避免死锁,与Object的w... 目录一、LockSupport1.1、LockSupport函数列表1.2、基本使用先 park 再 unpa

SpringBoot集成MyBatis实现SQL拦截器的实战指南

《SpringBoot集成MyBatis实现SQL拦截器的实战指南》这篇文章主要为大家详细介绍了SpringBoot集成MyBatis实现SQL拦截器的相关知识,文中的示例代码讲解详细,有需要的小伙伴... 目录一、为什么需要SQL拦截器?二、MyBATis拦截器基础2.1 核心接口:Interceptor