swagger2和knife4j的详细使用教程(入门级)_第1页
swagger2和knife4j的详细使用教程(入门级)_第2页
swagger2和knife4j的详细使用教程(入门级)_第3页
swagger2和knife4j的详细使用教程(入门级)_第4页
swagger2和knife4j的详细使用教程(入门级)_第5页
已阅读5页,还剩21页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

第swagger2和knife4j的详细使用教程(入门级)目录1、swagger介绍2、swagger常用注解3、swagger入门案例4、knife4j介绍5、knife4j入门案例总结入门级swagger2和knife4j的详细使用

重要的使事情说三遍

重要的使事情说三遍

重要的使事情说三遍

使用swagge或knife4j都有与springboot的版本兼容问题,该文章使用的springboot版本是2.2.2.RELEASE版本,如果高版本可能会出现启动报错

1、swagger介绍

相信无论是前端还是后端开发,都或多或少地被接口文档折磨过。前端经常抱怨后端给的接口文档与实际情况不一致。后端又觉得编写及维护接口文档会耗费不少精力,经常来不及更新。其实无论是前端调用后端,还是后端调用后端,都期望有一个好的接口文档。但是这个接口文档对于程序员来说,就跟注释一样,经常会抱怨别人写的代码没有写注释,然而自己写起代码起来,最讨厌的,也是写注释。所以仅仅只通过强制来规范大家是不够的,随着时间推移,版本迭代,接口文档往往很容易就跟不上代码了。

使用Swagger你只需要按照它的规范去定义接口及接口相关的信息。再通过Swagger衍生出来的一系列项目和工具,就可以做到生成各种格式的接口文档,生成多种语言的客户端和服务端的代码,以及在线接口调试页面等等。这样,如果按照新的开发模式,在开发新版本或者迭代版本的时候,只需要更新Swagger描述文件,就可以自动生成接口文档和客户端服务端代码,做到调用端代码、服务端代码以及接口文档的一致性。

为了简化swagger的使用,Spring框架对swagger进行了整合,建立了Spring-swagger项目,后面改成了现在的Springfox。通过在项目中引入Springfox,可以扫描相关的代码,生成描述文件,进而生成与代码一致的接口文档和客户端代码。

Springfox对应的maven坐标如下:

注意:swagger与springBoot的版本是有兼用性的,需要对应的版本号

dependency

groupIdio.springfox/groupId

artifactIdspringfox-swagger-ui/artifactId

version2.9.2/version

/dependency

dependency

groupIdio.springfox/groupId

artifactIdspringfox-swagger2/artifactId

version2.9.2/version

/dependency

2、swagger常用注解

注解说明@Api用在请求的类上,例如Controller,表示对类的说明@ApiModel用在类上,通常是实体类,表示一个返回响应数据的信息@ApiModelProperty用在属性上,描述响应类的属性@ApiOperation用在请求的方法上,说明方法的用途、作用@ApiImplicitParams用在请求的方法上,表示一组参数说明@ApiImplicitParam用在@ApiImplicitParams注解中,指定一个请求参数的各个方面

3、swagger入门案例

3.1、第一步:创建maven工程swagger_demo并配置pom.xml文件

xmlversion="1.0"encoding="UTF-8"

projectxmlns="/POM/4.0.0"

xmlns:xsi="/2001/XMLSchema-instance"

xsi:schemaLocation="/POM/4.0.0/xsd/maven-4.0.0.xsd"

modelVersion4.0.0/modelVersion

parent

groupIdorg.springframework.boot/groupId

artifactIdspring-boot-starter-parent/artifactId

version2.2.2.RELEASE/version

relativePath/

/parent

groupIdorg.example/groupId

artifactIdswagger_demo/artifactId

version1.0-SNAPSHOT/version

properties

piler.source8/piler.source

piler.target8/piler.target

/properties

dependencies

dependency

groupIdorg.springframework.boot/groupId

artifactIdspring-boot-starter-web/artifactId

/dependency

dependency

groupIdio.springfox/groupId

artifactIdspringfox-swagger-ui/artifactId

version2.9.2/version

/dependency

dependency

groupIdio.springfox/groupId

artifactIdspringfox-swagger2/artifactId

version2.9.2/version

/dependency

dependency

groupIdjectlombok/groupId

artifactIdlombok/artifactId

/dependency

/dependencies

/project

3.2、创建application.yml文件

server:

port:9000

3.3、第三步:创建实体类User和Menu

packagecom.zcl.entity;

importio.swagger.annotations.ApiModel;

importio.swagger.annotations.ApiModelProperty;

importlombok.Data;

*项目名称:swagger_demo

*描述:用户实体类

*@authorzhong

*@date2025-08-296:50

@Data

@ApiModel(value="用户实体",description="用户响应实体")

publicclassUser{

@ApiModelProperty(value="主键")

privateintid;

@ApiModelProperty(value="姓名")

privateStringname;

@ApiModelProperty(value="年龄")

privateintage;

@ApiModelProperty(value="地址")

privateStringaddress;

packagecom.zcl.entity;

importio.swagger.annotations.ApiModel;

importio.swagger.annotations.ApiModelProperty;

importlombok.Data;

*项目名称:swagger_demo

*描述:菜单实体类

*@authorzhong

*@date2025-08-296:49

@Data

@ApiModel(value="菜单实体",discriminator="菜单实体描述")

publicclassMenu{

@ApiModelProperty(value="主键")

privateintid;

@ApiModelProperty(value="菜单名称")

privateStringname;

3.4、第四步:创建UserController和MenuController

packagecom.zcl.controller.user;

importcom.zcl.entity.User;

importio.swagger.annotations.Api;

importio.swagger.annotations.ApiImplicitParam;

importio.swagger.annotations.ApiImplicitParams;

importio.swagger.annotations.ApiOperation;

importorg.springframework.web.bind.annotation.*;

importjava.util.ArrayList;

importjava.util.List;

*项目名称:swagger_demo

*描述:用户控制器

*@authorzhong

*@date2025-08-296:55

@Api(value="用户控制器")

@RestController

@RequestMapping("/user")

publicclassUserController{

@GetMapping("/getUsers")

@ApiOperation(value="查询所有用户",notes="查询所有用户信息")

publicListUsergetAllUsers(){

Useruser=newUser();

user.setId(100);

user.setName("itcast");

user.setAge(20);

user.setAddress("bj");

ListUserlist=newArrayList();

list.add(user);

returnlist;

@PostMapping("/save")

@ApiOperation(value="新增用户",notes="新增用户信息")

publicStringsave(@RequestBodyUseruser){

return"OK";

@PutMapping("/update")

@ApiOperation(value="修改用户",notes="修改用户信息")

publicStringupdate(@RequestBodyUseruser){

return"OK";

@DeleteMapping("/delete")

@ApiOperation(value="删除用户",notes="删除用户信息")

publicStringdelete(intid){

return"OK";

@ApiImplicitParams({

@ApiImplicitParam(name="pageNum",value="页码",

required=true,type="Integer"),

@ApiImplicitParam(name="pageSize",value="每页条数",

required=true,type="Integer"),

@ApiOperation(value="分页查询用户信息")

@GetMapping(value="page/{pageNum}/{pageSize}")

publicStringfindByPage(@PathVariableIntegerpageNum,

@PathVariableIntegerpageSize){

return"OK";

packagecom.zcl.controller.menu;

importcom.zcl.entity.Menu;

importio.swagger.annotations.Api;

importio.swagger.annotations.ApiImplicitParam;

importio.swagger.annotations.ApiImplicitParams;

importio.swagger.annotations.ApiOperation;

importorg.springframework.web.bind.annotation.*;

importjava.util.ArrayList;

importjava.util.List;

*项目名称:swagger_demo

*描述:菜单控制器

*@authorzhong

*@date2025-08-297:00

@Api(tags="菜单控制器")

@RestController

@RequestMapping("/menu")

publicclassMenuController{

@GetMapping("/getMenus")

@ApiOperation(value="查询所有菜单",notes="查询所有菜单信息")

publicListMenugetMenus(){

Menumenu=newMenu();

menu.setId(100);

menu.setName("itcast");

ListMenulist=newArrayList();

list.add(menu);

returnlist;

@PostMapping("/save")

@ApiOperation(value="新增菜单",notes="新增菜单信息")

publicStringsave(@RequestBodyMenumenu){

return"OK";

@PutMapping("/update")

@ApiOperation(value="修改菜单",notes="修改菜单信息")

publicStringupdate(@RequestBodyMenumenu){

return"OK";

@DeleteMapping("/delete")

@ApiOperation(value="删除菜单",notes="删除菜单信息")

publicStringdelete(intid){

return"OK";

@ApiImplicitParams({

@ApiImplicitParam(name="pageNum",value="页码",

required=true,type="Integer"),

@ApiImplicitParam(name="pageSize",value="每页条数",

required=true,type="Integer"),

@ApiOperation(value="分页查询菜单信息")

@GetMapping(value="page/{pageNum}/{pageSize}")

publicStringfindByPage(@PathVariableIntegerpageNum,

@PathVariableIntegerpageSize){

return"OK";

3.5、第五步:创建配置类SwaggerAutoConfiguration

packagecom.zcl.config;

importorg.springframework.context.annotation.Bean;

importorg.springframework.context.annotation.Configuration;

importspringfox.documentation.builders.ApiInfoBuilder;

importspringfox.documentation.builders.RequestHandlerSelectors;

importspringfox.documentation.service.ApiInfo;

importspringfox.documentation.service.Contact;

importspringfox.documentation.spi.DocumentationType;

importspringfox.documentation.spring.web.plugins.Docket;

importspringfox.documentation.swagger2.annotations.EnableSwagger2;

*项目名称:swagger_demo

*描述:swagger自动配置类

*@authorzhong

*@date2025-08-297:04

@Configuration

@EnableSwagger2

publicclassSwaggerAutoConfiguration{

@Bean

publicDocketcreateRestApi1(){

Docketdocket=newDocket(DocumentationType.SWAGGER_2)

.apiInfo(apiInfo()).groupName("用户接口组")

.select()

//为当前包路径

.apis(RequestHandlerSelectors.basePackage("com.zcl.controller.user"))

.build();

returndocket;

@Bean

publicDocketcreateRestApi2(){

Docketdocket=newDocket(DocumentationType.SWAGGER_2)

.apiInfo(apiInfo()).groupName("菜单接口组")

.select()

//为当前包路径

.apis(RequestHandlerSelectors.basePackage("com.zcl.controller.menu"))

.build();

returndocket;

//构建api文档的详细信息

privateApiInfoapiInfo(){

returnnewApiInfoBuilder()

//页面标题

.title("API接口文档")

//创建人

.contact(newContact("雕刻笔记","http://xiaozhong01.top",""))

//版本号

.version("1.0")

//描述

.description("API描述")

.build();

注意:如果不需要进行分组,可以将后面的createRestApi2()进行删除就剩余一个组了,并将.groupName(用户接口组)分组描述去掉以及将扫描控制器包修改即可

3.6、第六步:创建启动类SwaggerApplication

packagecom.zcl;

importorg.springframework.boot.SpringApplication;

importorg.springframework.boot.autoconfigure.SpringBootApplication;

*项目名称:swagger_demo

*描述:swagger项目启动类

*@authorzhong

*@date2025-08-297:13

@SpringBootApplication

publicclassSwaggerApplication{

publicstaticvoidmain(String[]args){

SpringApplication.run(SwaggerApplication.class,args);

3.7、项目启动

执行启动类main方法启动项目,访问地址:http://localhost:9000/swagger-ui.html

4、knife4j介绍

knife4j是为JavaMVC框架集成Swagger生成Api文档的增强解决方案,前身是swagger-bootstrap-ui,取名knife4j是希望它能像一把匕首一样小巧,轻量,并且功能强悍!其底层是对Springfox的封装,使用方式也和Springfox一致,只是对接口文档UI进行了优化。

核心功能:

文档说明:根据Swagger的规范说明,详细列出接口文档的说明,包括接口地址、类型、请求示例、请求参数、响应示例、响应参数、响应码等信息,对该接口的使用情况一目了然。在线调试:提供在线接口联调的强大功能,自动解析当前接口参数,同时包含表单验证,调用参数可返回接口响应内容、headers、响应时间、响应状态码等信息,帮助开发者在线调试。

5、knife4j入门案例

第一步:创建maven工程knife4j_demo并配置pom.xml文件

xmlversion="1.0"encoding="UTF-8"

projectxmlns="/POM/4.0.0"

xmlns:xsi="/2001/XMLSchema-instance"

xsi:schemaLocation="/POM/4.0.0/xsd/maven-4.0.0.xsd"

modelVersion4.0.0/modelVersion

parent

groupIdorg.springframework.boot/groupId

artifactIdspring-boot-starter-parent/artifactId

version2.2.2.RELEASE/version

relativePath/

/parent

groupIdorg.example/groupId

artifactIdknife4j/artifactId

version1.0-SNAPSHOT/version

properties

piler.source8/piler.source

piler.target8/piler.target

/properties

dependencies

dependency

groupIdorg.springframework.boot/groupId

artifactIdspring-boot-starter-web/artifactId

/dependency

dependency

groupIdcom.github.xiaoymin/groupId

artifactIdknife4j-spring-boot-starter/artifactId

version2.0.1/version

/dependency

dependency

groupIdjectlombok/groupId

artifactIdlombok/artifactId

/dependency

/dependencies

/project

第二步:创建实体类User和Menu

packagecom.zcl.entity;

importio.swagger.annotations.ApiModel;

importio.swagger.annotations.ApiModelProperty;

importlombok.Data;

*项目名称:swagger_demo

*描述:菜单实体类

*@authorzhong

*@date2025-08-296:49

@Data

@ApiModel(value="菜单实体",discriminator="菜单实体描述")

publicclassMenu{

@ApiModelProperty(value="主键")

privateintid;

@ApiModelProperty(value="菜单名称")

privateStringname;

packagecom.zcl.entity;

importio.swagger.annotations.ApiModel;

importio.swagger.annotations.ApiModelProperty;

importlombok.Data;

*项目名称:swagger_demo

*描述:用户实体类

*@authorzhong

*@date2025-08-296:50

@Data

@ApiModel(value="用户实体",description="用户响应实体")

publicclassUser{

@ApiModelProperty(value="主键")

privateintid;

@ApiModelProperty(value="姓名")

privateStringname;

@ApiModelProperty(value="年龄")

privateintage;

@ApiModelProperty(value="地址")

privateStringaddress;

第三步:创建UserController和MenuController

控制器与入门的swagger2是一样的,直接复制下来

第四步:创建接口文档配置属性类SwaggerProperties

由于上一个swagger_demo的接口文档配置文件是写死在项目代码中的,不利于后面的开发与维护,使用knife4j时并将相关的属性配置以yml全局的方式灵活的进行配置,方便进行修改

packagecom.zcl.config;

importlombok.Data;

importperties.ConfigurationProperties;

importjava.util.ArrayList;

importjava.util.LinkedHashMap;

importjava.util.List;

importjava.util.Map;

*项目名称:knife4j

*描述:配置属性类,用于封装yml配置文件中关于接口相关的配置文件

*@authorzhong

*@date2025-08-297:58

@Data

@ConfigurationProperties(prefix="knife.swagger")

publicclassSwaggerProperties{

/**标题*/

privateStringtitle="在线文档";

/**自定义组名*/

privateStringgroup="";

/**描述*/

privateStringdescription="在线文档";

/**版本*/

privateStringversion="1.0";

/**联系人*/

privateContactcontact=newContact();

/**swagger会解析的包路径*/

privateStringbasePackage="com.zcl";

/**swagger会解析的url规则*/

privateListStringbasePath=newArrayList();

/**在basePath基础上需要排除的url规则*/

privateListStringexcludePath=newArrayList();

/**分组文档*/

privateMapString,DocketInfodocket=newLinkedHashMap();

publicStringgetGroup(){

if(group==null||"".equals(group)){

returntitle;

returngroup;

@Data

publicstaticclassDocketInfo{

/**标题*/

privateStringtitle="在线文档";

/**自定义组名*/

privateStringgroup="";

/**描述*/

privateStringdescription="在线文档";

/**版本*/

privateStringversion="1.0";

/**联系人*/

privateContactcontact=newContact();

/**swagger会解析的包路径*/

privateStringbasePackage="com.zcl";

/**swagger会解析的url规则*/

privateListStringbasePath=newArrayList();

/**在basePath基础上需要排除的url规则*/

privateListStringexcludePath=newArrayList();

/**分组文档*/

privateMapString,DocketInfodocket=newLinkedHashMap();

publicStringgetGroup(){

if(group==null||"".equals(group)){

returntitle;

returngroup;

@Data

publicstaticclassContact{

/**联系人*/

privateStringname="pinda";

/**联系人url*/

privateStringurl="";

/**联系人email*/

privateStringemail="";

第五步:创建application.yml文件

该配置文件的属性是对应上面的配置文件属性的如果不对上就不会被读取到

下面重点的是对【docket】进行map分组的属性配置

privateMapString,DocketInfodocket=newLinkedHashMap();

不进行分组的配置

server:

port:7788

knife:

swagger:

enabled:true#是否启用swagger的开关

title:knife4j测试文档

description:knife4j测试文档描述

version:v1.0.0

basePackage:com.zcl.controller

进行分组的配置

server:

port:7788

knife:

swagger:

enabled:true#是否启用swagger的开关

title:knife4j测试文档

description:knife4j测试文档描述

version:v1.0.0

docket:#进行分组

user:#key

#value

title:用户模块

base-package:com.zcl.controller.user

menu:

title:菜单模块

base-package:com.zcl.controller.menu

注意:上面配置文件中的enabled属性是对应着下面配置类中【@ConditionalOnProperty】通过注解判断是否符合条件才让配置类生效

第六步:创建配置类SwaggerAutoConfiguration

该配置类需要使到上面创建的SwaggerProperties生效以及需要启用swagger注解

packagecom.zcl.config;

importmon.base.Predicate;

importmon.base.Predicates;

importorg.springframework.beans.BeansException;

importorg.springframework.beans.factory.BeanFactory;

importorg.springframework.beans.factory.BeanFactoryAware;

importorg.springframework.beans.factory.config.ConfigurableBeanFactory;

importorg.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

importperties.EnableConfigurationProperties;

importorg.springframework.context.annotation.Bean;

importorg.springframework.context.annotation.Configuration;

importspringfox.documentation.builders.ApiInfoBuilder;

importspringfox.documentation.builders.PathSelectors;

importspringfox.documentation.builders.RequestHandlerSelectors;

importspringfox.documentation.service.ApiInfo;

importspringfox.documentation.service.Contact;

importspringfox.documentation.spi.DocumentationType;

importspringfox.documentation.spring.web.plugins.Docket;

importspringfox.documentation.swagger2.annotations.EnableSwagger2;

importjavax.annotation.Resource;

importjava.util.ArrayList;

importjava.util.List;

importjava.util.Map;

importjava.util.Set;

*项目名称:knife4j

*描述:配置类

*@authorzhong

*@date2025-08-298:22

@Configuration

@EnableConfigurationProperties(SwaggerProperties.class)

@EnableSwagger2

@ConditionalOnProperty(name="knife.swagger.enabled",havingValue="true",

matchIfMissing=true)

publicclassSwaggerAutoConfigurationimplementsBeanFactoryAware{

privateBeanFactorybeanFactory;

*通过类型注入去查找beanFactory

*@parambeanFactory

*@throwsBeansException

@Override

publicvoidsetBeanFactory(BeanFactorybeanFactory)throwsBeansException{

this.beanFactory=beanFactory;

*注入自动配置属性类

@Resource

privateSwaggerPropertiesswaggerProperties;

*遍历swaggerProperties属性配置的内容,转换成List集合【方便判断有没有进行分组,没有分组就一个list,分组就有多个】

*使用@ConditionalOnProperty条件注入,bean工程有就不创建

*@return

@Bean

@ConditionalOnMissingBean

publicListDocketcreateRestApi(){

//强转beanFactory为可配置的bean工厂

ConfigurableBeanFactoryconfigurableBeanFactory=

(ConfigurableBeanFactory)beanFactory;

//创建返回的list集合

ListDocketdocketList=newArrayList();

//获取到分组的对象如果为空就是不分组

if(swaggerProperties.getDocket().isEmpty()){

Docketdocket=createDocket(swaggerProperties);

docketList.add(docket);

}else{

//存在分组对象

//获取到key【user\menu】

SetStringkeySet=swaggerProperties.getDocket().keySet();

//遍历key获取到对应的value

for(Stringkey:keySet){

//获取到info

SwaggerProperties.DocketInfodocketInfo=swaggerProperties.getDocket().get(key);

ApiInfoapiInfo=newApiInfoBuilder()

//页面标题

.title(docketInfo.getTitle())

//创建人

.contact(newContact(docketInfo.getContact().getName(),

docketInfo.getContact().getUrl(),

docketInfo.getContact().getEmail()))

//版本号

.version(docketInfo.getVersion())

//描述

.description(docketInfo.getDescription())

.build();

//base-path处理

//当没有配置任何path的时候,解析/**

if(docketInfo.getBasePath().isEmpty()){

docketInfo.getBasePath().add("/**");

ListPredicateStringbasePath=newArrayList();

for(Stringpath:docketInfo.getBasePath()){

basePath.add(PathSelectors.ant(path));

//exclude-path处理

ListPredicateStringexcludePath=newArrayList();

for(Stringpath:docketInfo.getExcludePath()){

excludePath.add(PathSelectors.ant(path));

Docketdocket=newDocket(DocumentationType.SWAGGER_2)

.apiInfo(apiInfo)

.groupName(docketInfo.getGroup())

.select()

//为当前包路径

.apis(RequestHandlerSelectors.basePackage(docketInfo.getBasePackage()))

.paths(Predicates.and(Predicates.not(Predicates.or(excludePath)),Predicates.or(basePath)))

.build();

configurableBeanFactory.registerSingleton(key,docket);

docket

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论