SpringBoot+Swagger2实现API文档+lombok工具包简化代码

2023-10-26

Swagger UI:提供了一个可视化的UI页面展示描述文件。
接口的调用方、测试、项目经理等都可以在该页面中对相关接口进行查阅和做一些简单的接口请求。
该项目支持在线导入描述文件和本地部署UI项目。
lombok是一个可以帮助我们简化java代码编写的工具类,尤其是简化javabean的编写,
即通过采用注解的方式,消除代码中的构造方法,getter/setter等代码,使我们写的类更加简洁

1、在项目中的pom.xml文件中加入maven依赖包

		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.8.0</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.8.0</version>
		</dependency>
		<!--lombok一个帮助我们简化javabean代码编写的工具包-->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.6</version>
			<scope>provided</scope>
		</dependency>

2、添加Swagger配置类Swagger2Config

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
// 可指定配置文件,比如当使用prod生产环境的配置文件时该类不生效
@Profile({"dev", "test"})
public class Swagger2Config {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // 为当前控制层包路径
                .apis(RequestHandlerSelectors.basePackage("com.tool.controller"))
                .paths(PathSelectors.any())
                .build();
    }
	
    /**
     * 构建 api文档的详细信息函数
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 页面标题
                .title("用户模块服务")
                // 描述
                .description("接口文档")
                .version("1.0")
                .build();
    }
}

3、在controller类中加上相应的注解

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

// @Api注解是swagger里的,主要为类提供相关说明
@Api(tags = "人员控制层接口")
@RestController
@RequestMapping("/v1/user")
public class UserController {

	@Autowired
	private UserService userService;

	/**
	 * @ApiOperation注解是swagger里的,主要为接口提供相关说明
	 */
	@ApiOperation(value = "根据工号查看人员详情")
	@PostMapping("/findUserDetailById")
	public ResultDto findUserDetailById(@RequestParam("userId") String userId) {
		return userService.findUserDetailById(userId);
	}
	
}

4、在启动类中加入@EnableSwagger2注解

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
	
}

启动项目后,访问http://localhost:8080/swagger-ui.html 看看显示效果:出现下面页面则成功

当项目的静态文件路径被修改后,就会发生访问不到的情况

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Thu Aug 01 09:50:09 CST 2019
There was an unexpected error (type=Not Found, status=404).
No message available

因为swagger-ui.html 是在springfox-swagger-ui.jar里的,
因为修改了路径Spring Boot不会自动把/swagger-ui.html这个路径映射到对应的目录META-INF/resources/下面。
所以我们修改SpringBoot配置类,为Swagger建立新的静态文件路径映射就可以了

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

	@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

可以在实体类的类名上加入@ApiModel,变量使用@ApiModelProperty

@ApiModel作为类的描述
@ApiModelProperty作为字段的描述
@Data 注解相当于 Getter + Setter + ToString + @RequiredArgsConstrutor
需要注意的是:@ApiModel内的注释不要出现相同否则会将相同的vo内的字段进行合并

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@ApiModel(value = "User", description = "人员信息描述")
@Data
public class User {
    
    @ApiModelProperty("工号")
    private String userId;
    
    @ApiModelProperty("姓名")
    private String userName;
    
}

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringBoot+Swagger2实现API文档+lombok工具包简化代码 的相关文章

随机推荐

  • C# Modbus CRC校验

    Modbus CRC校验 直接输入byte 输出bool public static bool CRC Check byte byteData bool Flag false byte CRC new byte 2 UInt16 wCrc
  • React 深入系列1:React 中的元素、组件、实例和节点

    React 深入系列 深入讲解了React中的重点概念 特性和模式等 旨在帮助大家加深对React的理解 以及在项目中更加灵活地使用React React 中的元素 组件 实例和节点 是React中关系密切的4个概念 也是很容易让React
  • 从0搭建react项目

    一 快速开始 全局安装脚手架 npm install g create react app 复制代码 通过脚手架搭建项目 create react app lt 项目名称 gt 复制代码 开始项目 cd lt 项目名 gt npm run
  • 音频-什么是PCM编码格式?

    PCM中文称脉冲编码调制 Pulse Code Modulation 是70年代末发展起来的 记录媒体之一的CD 在80年代初由飞利浦和索尼公司共同推出 脉码调制的音频格式也被DVD A所采用 它支持立体声和5 1环绕声 1999年由DVD
  • 正则表达式-----小数点后允许有两位数字

    校验是否全由数字组成 function isDigit s var patrn 0 9 1 20 if patrn exec s return false return true 校验登录名 只能输入5 20个以字母开头 可带数字 的字串
  • eclipse关联spring源码

    在Eclipse中如何关联spring framework的文档和源代码 1 到官方网站去下载spring framework的jar包 spring framework jar包的下载地址是 http repo spring io rel
  • 解决ubuntu18.04卡在“starting Gnome Display Manager“

    我提前安装了ssh 所以可以ssh进行下面的操作 如果你没有 你可以进入命令行 或者其他模式进行下面的操作 好多人都遇到这个问题 我提前说下 安装驱动之前 最好安装个ssh ssh 怎么用自己百度吧 这样万一你的电脑卡住了 你找个别人的电脑
  • autoApprove

    服务端最主要的一个配置就是使用 EnableAuthorizationServer 注解 该注解的作用就是引入了一些 OAuth2 相关的端点 包含以下的端点 AuthorizationEndpoint 根据用户认证获得授权码 有下面两个方
  • 工作日记:JavaScript生成随机色

    不多啰啰 直接上硬货 获取指定闭区间的随机数 param min 最小值 param max 最大值 returns number export function getRandomNum min max let result if min
  • 2007.08.21单链表的运算(查找,插入,删除)

    2 查找 1 按序号查找 在单链表中 由于每个结点的存储位置都放在其前一结点的next域中 因而即使知道被访问结点的序号i 也不能像顺序表那样直接按序号i访问一维数组中的相应元素 实现随机存取 而只能从链表的头指针出发 顺链域next诸葛结
  • 代理记账公司怎样找客户?教你一个简单又有效的方法

    针对许多初创期公司而言 资金和人力资源管理都非常欠缺 重心点更偏重于业务流程自身 因而会将会计等有关问题交到代理记账公司 实际上这个是较为聪明的作法 代理记账是指将本公司的财务核算 做账 纳税申报等一系列的工作中所有委派给技术专业做账公司进
  • C语言之求两个整数之和

    include
  • uva 120(排序,检索)

    题目 Stacks and Queues are often considered the bread and butter of data structures and find use in architecture parsing o
  • Tesseract 最简单的图片文字识别

    Tesseract是一个开源的库 下面写一个最简单的实例 include stdafx h include strngs h include baseapi h include
  • python: more Layer Architecture and its Implementation in Python and mysql 8.0

    mysql 8 0 drop table DuStudentList 学生表 create table DuStudentList StudentId INT NOT NULL AUTO INCREMENT comment 主键id 自动增
  • [转]SQL的一对多,多对一,一对一,多对多的含义以及使用方法。

    1 一对多 比如说一个班级有很多学生 可是这个班级只有一个班主任 在这个班级中随便找一个人 就会知道他们的班主任是谁 知道了这个班主任就会知道有哪几个学生 这里班主任和学生的关系就是一对多 2 多对一 比如说一个班级有很多学生 可是这个班级
  • Masm for Windows集成开发环境编写汇编程序

    由于最近在学习汇编 用的软件是一款叫 Masm for Windows集成开发环境 但是发现该软件的资料比较少 对于我们这样刚刚学习汇编的同学 我查找了很多资料 下面主要是介绍该工具及2个汇编的基本程序 一 软件的使用 下面是阅读完四川大学
  • 网络编程(JavaEE初阶系列10)

    目录 前言 1 网络编程的基础 1 1为什么需要网络编程 1 2什么是网络编程 1 3网络编程中的基本概念 1 3 1发送端和接收端 1 3 2请求和响应 1 3 3客户端和服务端 2 Socket套接字 2 1概念 2 2分类 3 UDP
  • k8s docker集群搭建

    一 Kubernetes系列之介绍篇 Kubernetes介绍 1 背景介绍 云计算飞速发展 IaaS PaaS SaaS Docker技术突飞猛进 一次构建 到处运行 容器的快速轻量 完整的生态环境 2 什么是kubernetes 首先
  • SpringBoot+Swagger2实现API文档+lombok工具包简化代码

    Swagger UI 提供了一个可视化的UI页面展示描述文件 接口的调用方 测试 项目经理等都可以在该页面中对相关接口进行查阅和做一些简单的接口请求 该项目支持在线导入描述文件和本地部署UI项目 lombok是一个可以帮助我们简化java代