springboot项目使用Swagger RestAPI最佳说明文档

本文主要是介绍springboot项目使用Swagger RestAPI最佳说明文档,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

#springboot项目使用Swagger RestAPI最佳说明文档

我们在开发各种rest服务的时候,需要给出rest api的介绍使用。如果没有rest API的介绍使用文档,除了看源代码几乎没人知道怎么使用。那么如何来编写rest API的说明文档了? 当然我们可以自己写一个类似javadoc的工具,然后每次构建的时候生成对应的html, 或者字节开发注解,然后根据一定规则生成rest doc文档, 那么有没有一种开源的,统一并且便捷好用的rest 说明文档工具了? 当然有,那就是Swagger.

我们先看看Swagger官方网站是如何介绍该项目的。
Swagger–The World’s Most Popular API Tooling, 世界上最流行的API工具。

下面我们直接进入正题,如何在springboot项目中使用Swagger。总共分为三部
第一步,引入swagger依赖
第二部,在spring-boot中配置swagger-ui界面
第三步,提供API文档页基本信息
第四步,给rest API编写文档
项目在这里。 欢迎下载和关注, 谢谢!

#第一步引入swagger依赖
在pom文件中添加如下依赖

        <!-- Use Swagger for rest API --><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>

#第二步 在spring-boot中配置swagger-ui界面
在我们项目中增加一个类WebMvcConfig。

package com.yq.demo.config;import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/js/**").addResourceLocations("classpath:/js/");registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");}}

#第三步 提供API文档页基本信息
也是添加一个新类
package com.yq.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.service.Contact;
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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2 {
//swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//为当前包路径
.apis(RequestHandlerSelectors.basePackage(“com.yq.demo.controller”))
.paths(PathSelectors.any())
.build();
}
//构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(“Spring Boot 测试使用 Swagger2 构建RESTful API”)
.contact(new Contact(“EricYang”, “https://github.com/xyz/abc.git”, "test1@163.com"))
.version(“1.0”)
.description(“User API 描述”)
.build();
}

}

#第四步,给rest API编写文档
这一步是我们的主要工作,这里我们给两个Controller编写api文档
第一个是HelloWorldController, 它有一个get rest api显示Hello World

    @ApiOperation(value = "hello demo", notes = "just for demo")@GetMapping(value = "/hello", produces = "text/plain;charset=UTF-8")public String hello() {return "Hello World";}

可以看到@GetMapping(value = “/hello”, produces = “text/plain;charset=UTF-8”)
其中的value = “/hello"就是我们rest的路径, 因为我们返回的是字符串,所以使用"text/plain;charset=UTF-8”
下面是另外一个UserController, API比较多, 我们选择其中2个,项目类容可以参看源代码

    @ApiOperation(value = "add new user", notes = "add new user to system")@ApiImplicitParams({@ApiImplicitParam(name = "userName", value = "userName", required = true, dataType = "String", paramType = "query"),@ApiImplicitParam(name = "password", value = "密码", required = true ,dataType = "String", paramType = "query"),@ApiImplicitParam(name = "fullName", value = "fullName", required = true ,dataType = "String", paramType = "query"),@ApiImplicitParam(name = "email", value = "email", required = true ,dataType = "String", paramType = "query"),@ApiImplicitParam(name = "usertype", allowableValues="1,2,3", required = false ,dataType = "int", paramType = "query"),@ApiImplicitParam(name = "dateformat", value = "dateformat", required = false ,dataType = "String", paramType = "query"),@ApiImplicitParam(name = "timeforamt", value = "timeforamt", required = false ,dataType = "String", paramType = "query"),@ApiImplicitParam(name = "timezone", value = "timezone", required = false ,dataType = "String", paramType = "query"),@ApiImplicitParam(name = "language", value = "language", required = false ,dataType = "String", paramType = "query")})@PostMapping(value = "/add", produces = "application/json;charset=UTF-8")public  @ResponseBody User addNewUser(@RequestParam String userName,@RequestParam String password,@RequestParam String fullName,@RequestParam String email,@RequestParam Integer usertype,@RequestParam(value = "dateformat", defaultValue = "yyyy-MM-dd") String dateformat,@RequestParam(value = "timeforamt", defaultValue = "HH:mm:ss") String timeforamt,@RequestParam(value = "timezone", defaultValue = "GMT+8") String timezone,@RequestParam(value = "language", defaultValue = "zh_CN") String language) {User user = new User();user.setUsername(userName);user.setFullname(fullName);user.setEmail(email);user.setLanguage(language);user.setPassword(password);user.setActive(1);user.setUserType(usertype);user.setCan_delete(1);user.setTimeZone(timezone);user.setTimeFormat(timeforamt);user.setDateFormat(dateformat);userRepository.save(user);return user;}

下面这个是根据FullName进行查询的例子。其中只有一个path的参数fullname

    @ApiOperation(value = "findByFullName", notes = "find by fullName")@ApiImplicitParam(name = "fullname", value = "fullname", required = true, dataType = "String", paramType = "path")@GetMapping(value = "/findByFullName/{fullname}", produces = "application/json;charset=UTF-8")@ResponseBodypublic User getUserByFullName(@PathVariable String fullname){User user = userRepository.getByFullName(fullname);return user;}

最后运行我们的项目, 在浏览器打开http://127.0.0.1:8080/swagger-ui.html

示例图1
这里写图片描述

选择运行findByFullName
这里写图片描述

这篇关于springboot项目使用Swagger RestAPI最佳说明文档的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


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

相关文章

SpringBoot中六种批量更新Mysql的方式效率对比分析

《SpringBoot中六种批量更新Mysql的方式效率对比分析》文章比较了MySQL大数据量批量更新的多种方法,指出REPLACEINTO和ONDUPLICATEKEY效率最高但存在数据风险,MyB... 目录效率比较测试结构数据库初始化测试数据批量修改方案第一种 for第二种 case when第三种

Java docx4j高效处理Word文档的实战指南

《Javadocx4j高效处理Word文档的实战指南》对于需要在Java应用程序中生成、修改或处理Word文档的开发者来说,docx4j是一个强大而专业的选择,下面我们就来看看docx4j的具体使用... 目录引言一、环境准备与基础配置1.1 Maven依赖配置1.2 初始化测试类二、增强版文档操作示例2.

一文详解如何使用Java获取PDF页面信息

《一文详解如何使用Java获取PDF页面信息》了解PDF页面属性是我们在处理文档、内容提取、打印设置或页面重组等任务时不可或缺的一环,下面我们就来看看如何使用Java语言获取这些信息吧... 目录引言一、安装和引入PDF处理库引入依赖二、获取 PDF 页数三、获取页面尺寸(宽高)四、获取页面旋转角度五、判断

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

C++中assign函数的使用

《C++中assign函数的使用》在C++标准模板库中,std::list等容器都提供了assign成员函数,它比操作符更灵活,支持多种初始化方式,下面就来介绍一下assign的用法,具有一定的参考价... 目录​1.assign的基本功能​​语法​2. 具体用法示例​​​(1) 填充n个相同值​​(2)

MySQL 迁移至 Doris 最佳实践方案(最新整理)

《MySQL迁移至Doris最佳实践方案(最新整理)》本文将深入剖析三种经过实践验证的MySQL迁移至Doris的最佳方案,涵盖全量迁移、增量同步、混合迁移以及基于CDC(ChangeData... 目录一、China编程JDBC Catalog 联邦查询方案(适合跨库实时查询)1. 方案概述2. 环境要求3.

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in