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 为例:
在这里插入图片描述
在这里插入图片描述

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

展开说说:Android列表之RecyclerView

RecyclerView 它是从Android5.0出现的全新列表组件&#xff0c;更加强大和灵活。用于显示列表形式 (list) 或者网格形式 (grid) 的数据&#xff0c;替代ListView和GridView成为Android主流的列表组件。可以说Android客户端只要有表格的地方就有RecyclerView。 RecyclerView 内…

【Android】Material TabLayout使用详解

基本用法 TabItem可以设置text&#xff0c;icon&#xff0c;layout三个属性 其它属性都通过TabLayout来统一设置 <com.google.android.material.tabs.TabLayout><com.google.android.material.tabs.TabItem/><com.google.android.material.tabs.TabItem/>…

VCS编译bug汇总

‘typedef’ is not expected to be used in this contex 注册前少了分号。 Scope resolution error resolution : 声明指针时 不能与类名同名&#xff0c;即 不能声明为adapter. cannot find member "type_id" 忘记注册了 拼接运算符使用 关键要加上1b&#xff0…

[MySQL]购物管理系统—简略版

本文内容需以MySQL支持 特别感谢baidu comate AI提供的少量虚拟数据 0.建库(建立数据库——utf8字符集&#xff0c;utf8_general_ci排序规则) 1.此项目ER图如下 2.DDLDML(共九表&#xff0c;27数据) SET FOREIGN_KEY_CHECKS 0;DROP TABLE IF EXISTS goods; CREATE TABLE g…

前端vue-cli相关知识与搭建过程(项目创建,组件路由)very 详细

一.关于vue-cli 1.什么是vue Vue (读音 /vju ː /&#xff0c;类似于 view) 是一套用于构建用户界面的渐进式框架。Vue 的核心库只关注视图层&#xff0c;不仅易于上手&#xff0c;还便于与第三方库或既有项目整合。 Vue.js 是前端的主流框架之一&#xff0c;和 Angular.js…

【公开数据集获取】

Open Images Dataset https://www.youtube.com/watch?vdLSFX6Jq-F0

一分钟彻底掌握java泛型

Java中的泛型&#xff08;Generics&#xff09; 在Java中&#xff0c;泛型是JDK 5引入的一个非常重要的特性&#xff0c;它允许你在定义类、接口和方法时使用类型参数&#xff08;type parameters&#xff09;。使用泛型的主要好处是可以提供编译时的类型检查&#xff0c;减少…

【M365运维】Outlook和Teams里不显示用户的组织架构

【问题】 由于一些误操作&#xff0c;把用户账户禁用并重新启用后&#xff0c;发现在Outlook和Teams里无法查看用户的组织结构图了。如下图所示&#xff1a; - 在Outlook 里&#xff0c;用户标签页的组织一直显示“正在加载..."&#xff0c;成员身份也是“找不到任何组。…

【GD32】08 - IIC(以SHT20为例)

GD32中的IIC 今天来了解一下GD32中的硬件IIC&#xff0c;其实我个人是觉得软件IIC比较方便的&#xff0c;不过之前文章里用的都是软件IIC&#xff0c;今天就算是走出自己的舒适圈&#xff0c;我们来了解了解GD32中的硬件IIC。 我这里用的型号是GD32F407&#xff0c;不同型号的…

等保测评初级简答题试题

基本要求&#xff0c;在应用安全层面的访问控制要求中&#xff0c;三级系统较二级系统增加的措施有哪些&#xff1f; 答&#xff1a;三级比二级增加的要求项有&#xff1a; 应提供对重要信息资源设置敏感标记的功能&#xff1b; 应按照安全策略严格控制用户对有敏感标记重要…

策略模式和状态模式

策略模式 在上下文中携带策略接口作为成员变量&#xff0c;在使用上下文之前需要设置策略setStrategy&#xff08;&#xff09;&#xff0c;然后使用策略接口成员变量来进行策略的执行。 步骤1&#xff1a;定义策略接口 // 策略接口 public interface Strategy {int execut…

猎豹WiFi

猎豹WiFi&#xff0c;记得刚安装完就一堆广告弹窗&#xff0c;然后删除了一些东西&#xff0c;不影响开热点的功能。 kwifi.zip - 蓝奏云

干涉阵型成图参数记录【robust】

robust 这个玩意经常忘记&#xff0c;就是取2的时候是更加显示大尺度的结构&#xff0c;取-2更加显示小尺度结果&#xff0c;一般取0就是正常就好了

真正要战胜的,不是困难,是自己

记录一些好的文字&#xff0c;希望可以和大家共勉。 一个人真正的成长&#xff0c;是战胜自己 不知你是否有这样的经历&#xff1a;曾经觉得一道题很难&#xff0c;但解出来后&#xff0c;发现其实并没那么难&#xff1b;曾经觉得一件事是不可能完成的&#xff0c;但历经千辛万…

vitest-前端单元测试

Vitest是一个轻量级、快速且功能强大的测试框架&#xff0c;特别适用于Vite项目&#xff0c;但也可以与其他前端项目&#xff08;如使用webpack构建的项目&#xff09;集成使用。Vitest提供极速的测试体验&#xff0c;并包含一系列用于编写和组织测试用例的API&#xff0c;如de…

vue项目中,pnpm不能用-解决

方法四&#xff1a;解决 PowerShell 执行策略问题 如果你决定继续使用 PowerShell&#xff0c;并且遇到执行策略问题&#xff0c;可以尝试以下方法解决&#xff1a; 永久更改执行策略&#xff1a; 在管理员权限的 PowerShell 中运行以下命令&#xff0c;以永久更改执行策略&am…

【Hive中常见的优化手段----数据采集!Join 优化!Hive索引!数据倾斜!mapreduce本地模式!map和reduce数量调整!】

前言&#xff1a; &#x1f49e;&#x1f49e;大家好&#xff0c;我是书生♡&#xff0c;今天主要和大家分享一下Hive中常见的优化手段----数据采集&#xff01;常见的Join 优化有哪几种&#xff01;什么是Hive索引&#xff01;数据怎么发生倾斜&#xff01;什么是mapreduce的本…

力扣每日一题 6/24 模拟 数组 单调栈

博客主页&#xff1a;誓则盟约系列专栏&#xff1a;IT竞赛 专栏关注博主&#xff0c;后期持续更新系列文章如果有错误感谢请大家批评指出&#xff0c;及时修改感谢大家点赞&#x1f44d;收藏⭐评论✍ 503.下一个更大元素II 【中等】 题目&#xff1a; 给定一个循环数组 nums…

数据分析师怎么去快速读一本书

背景&#xff1a;优秀的数据分析师怎么去快速读一本书 一本好书的判断依据 1.有没有再次印刷&#xff0c;三次印刷一般是好书 2.作者 快读选书顺序 1.目录->定位这是一本什么书 2.看内容的呈现形式&#xff0c;内容的各部分占比大概是什么类型的信息。 3.去看自己擅长的知…

使用原子子表创建可重用的子组件

原子子表是一个图形对象&#xff0c;可帮助您在Stateflow图表中创建独立的子部件。原子子表允许&#xff1a; 对具有多个状态或层次结构的图表进行微小更改后&#xff0c;模拟速度更快。 在多个图表和模型中重复使用相同的状态或子表。 易于团队开发&#xff0c;适用于在同一图…