目录
- kinfe4j
- 与Swagger的区别
- SpringBoot2.x整合kinfe4j
- 1.添加依赖
- 2.启动类注解
- 3.创建Knife4J配置类
- 4.实体类
- 5.接口
- admin
- 访问
- api
- 访问
- 常用注解汇总
- SpringBoot3.x整合Kinfe4j
- 启动报错
- 解决
- 1.更换依赖
- 2.启动类
- 3.配置
- 4.配置类
- 5.参数实体类
- 6.接口
- admin
- 访问
- api
- 访问
- 各版本注解参照
kinfe4j
- Knife4j(又称为 Swagger-Bootstrap-UI)是一个基于 Swagger 的 Java 接口文档生成工具,它提供了一套简单易用的界面来展示和调试接口文档。
- Swagger 是一种用于描述、构建和生成可视化 RESTful API 文档的工具。它通过注解在代码中定义接口信息,并通过解析代码生成接口文档,同时还提供了友好的界面供开发者查看和测试接口。
- 而 Knife4j 是 Swagger 的扩展工具,它在 Swagger 的基础上进行了功能和样式的优化,使得生成的接口文档更加美观、易读。
- 使用 Knife4j,开发者可以通过在代码中添加 Swagger 的注解,例如 @ApiOperation、@ApiParam 等,来定义接口的信息和参数。
- 然后,Knife4j 会根据这些注解生成接口文档,并提供一个友好的界面来展示和调试接口。开发者可以在界面中查看接口的详细信息、参数说明、返回值等,并可以直接在界面中测试接口。
- Knife4j 还提供了一些扩展功能,例如接口权限控制、参数校验、数据模型的可视化展示等,可以根据需要进行配置和使用。
总的来说,Knife4j 是一个能够根据代码注解生成美观易读的接口文档,并提供友好界面进行接口调试和测试的工具。它可以帮助开发者更好地编写、查看和调试接口文档,提高开发效率。
- 官网:https://doc.xiaominfo.com/
- GitHub:https://github.com/xiaoymin/swagger-bootstrap-ui
与Swagger的区别
Swagger | Knife4j | |
---|---|---|
UI界面 | Swagger默认的UI界面相对简洁,主要以接口列表和接口详情展示为主 | Knife4j使用了Bootstrap风格的UI界面,更加美观且提供了更多的交互功能,如接口调试、参数校验等。 |
配置灵活性 | Swagger的配置相对简单,可以通过注解来设置API的详细信息 | Knife4j提供了更多的扩展点,可以根据需要进行更加灵活的配置,如文档分组、权限控制等。 |
文档生成效果 | Swagger生成的API文档较为简洁,主要以接口的基本信息为主 | Knife4j在Swagger的基础上,增加了更多的展示功能,如接口说明、参数校验、示例请求、响应数据等,使得文档更加详细和友好。 |
Knife4j通过优化UI界面和改进微服务架构下的使用方式,提供了一种更加现代化和灵活的API文档管理解决方案,而Swagger则是一个更加通用和基础的接口管理工具。
-
Knife4j和Swagger的主要区别在于UI优化、微服务架构下的使用灵活性、以及功能扩展性。
-
Knife4j是在Swagger的基础上进行优化的一个开源项目,它主要针对Swagger的UI界面进行了改进,提供了更加炫酷和逼格高的界面,从而提升了用户体验。此外,Knife4j在微服务架构下的使用更加灵活,通过将后端Java代码和UI模块进行分离,使得在微服务架构下使用增强文档注解时更加方便。这种分离使得Knife4j能够更好地适应微服务架构的需求,尤其是在SpringCloud微服务项目中,只需要在网关层集成UI的jar包即可,从而提高了使用的便捷性。
-
相比之下,Swagger虽然也是一个功能强大的接口管理工具,提供了多种编程语言的前后端分离解决方案,并且在开发时通过注解编写注释,可以自动生成API文档。但是,Swagger在微服务架构下的使用可能显得有些臃肿,不够灵活。
SpringBoot2.x整合kinfe4j
1.添加依赖
<dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId><version>2.0.8</version>
</dependency>
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId>
</dependency>
2.启动类注解
@EnableKnife4j
@SpringBootApplication
@EnableKnife4j
public class DemoKnife4jApplication {public static void main(String[] args) {SpringApplication.run(DemoKnife4jApplication.class, args);}}
3.创建Knife4J配置类
package com.kgc.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;import java.util.ArrayList;
import java.util.List;/*** Swagger2配置信息* 这里分了两组显示* 第一组是api,当作用户端接口* 第二组是admin,当作后台管理接口* 也可以根据实际情况来减少或者增加组* @author: zjl* @datetime: 2024/6/14*/@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfig {private ApiInfo adminApiInfo() {return new ApiInfoBuilder().title("SpringBoot整合Knife4j-API文档").description("本文档描述了SpringBoot如何整合Knife4j").version("1.0").contact(new Contact("Susheng", "zhoujl.blog.csdn.net", "180xxxx8296@163.com")).build();}private ApiInfo webApiInfo() {return new ApiInfoBuilder().title("SpringBoot整合Knife4j-API文档").description("本文档描述了SpringBoot如何整合Knife4j").version("1.0").contact(new Contact("Susheng", "zhoujl.blog.csdn.net", "180xxxx8296@163.com")).build();}/*** 第一组:api* @return*/@Beanpublic Docket webApiConfig() {List<Parameter> pars = new ArrayList<>();ParameterBuilder tokenPar = new ParameterBuilder();tokenPar.name("userId").description("用户token")//.defaultValue(JwtHelper.createToken(1L, "admin")).defaultValue("1").modelRef(new ModelRef("string")).parameterType("header").required(false).build();pars.add(tokenPar.build());Docket webApi = new Docket(DocumentationType.SWAGGER_2).groupName("用户端接口").apiInfo(webApiInfo()).select()//只显示api路径下的页面.apis(RequestHandlerSelectors.basePackage("com.kgc")).paths(PathSelectors.regex("/api/.*")).build().globalOperationParameters(pars);return webApi;}/*** 第二组:admin* @return*/@Beanpublic Docket adminApiConfig() {List<Parameter> pars = new ArrayList<>();ParameterBuilder tokenPar = new ParameterBuilder();tokenPar.name("adminId").description("用户token").defaultValue("1").modelRef(new ModelRef("string")).parameterType("header").required(false).build();pars.add(tokenPar.build());Docket adminApi = new Docket(DocumentationType.SWAGGER_2).groupName("后台接口").apiInfo(adminApiInfo()).select()//只显示admin路径下的页面.apis(RequestHandlerSelectors.basePackage("com.kgc")).paths(PathSelectors.regex("/admin/.*")).build().globalOperationParameters(pars);return adminApi;}
}
4.实体类
package com.kgc.pojo;import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Builder;
import lombok.Data;/*** @author: zjl* @datetime: 2024/6/14*/
@ApiModel("用户实体类")
@Data
@Builder
public class User{@ApiModelProperty("用户Id")private Long id;@ApiModelProperty("用户账号")private String userCode;@ApiModelProperty("用户名称")private String userName;@ApiModelProperty("用户密码")private String userPassword;
}
5.接口
admin
package com.kgc.controller;import com.kgc.pojo.User;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** @author: zjl* @datetime: 2024/6/14* @desc: 复兴Java,我辈义不容辞*/
@Api(tags = "用户端控制器")
@RestController
@RequestMapping("/admin")
public class AdminController {@ApiOperation(value = "用户添加")@PostMapping("/save")@ApiResponses(value = {@ApiResponse(code = 200,message = "添加成功"),@ApiResponse(code = 500,message = "添加失败"),})public Map<String,Object> save(User user){Map<String,Object> resultMap = new HashMap<>();return resultMap;}@ApiOperation(value = "获取用户详情")@GetMapping("/detail")public User detail(@ApiParam(name = "id",value = "用户ID") Long id){User user = User.builder().id(1L).userCode("admin").userName("系统管理员").build();return user;}
}
访问
访问地址:http://127.0.0.1:8080/doc.html
api
package com.kgc.controller;import com.kgc.pojo.User;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** @author: zjl* @datetime: 2024/6/14* @desc: 复兴Java,我辈义不容辞*/
@Api(tags = "用户端控制器-Api")
@RestController
@RequestMapping("/api")
public class ApiController {@ApiOperation(value = "用户添加")@PostMapping("/save")@ApiResponses(value = {@ApiResponse(code = 200,message = "添加成功"),@ApiResponse(code = 500,message = "添加失败"),})public Map<String,Object> save(User user){Map<String,Object> resultMap = new HashMap<>();return resultMap;}@ApiOperation(value = "获取用户详情")@GetMapping("/detail")public User detail(@ApiParam(name = "id",value = "用户ID") Long id){User user = User.builder().id(1L).userCode("admin").userName("系统管理员").build();return user;}
}
访问
常用注解汇总
-
@Api:用于标注Controller类,表示该类是Swagger资源。
-
@ApiOperation:用于标注Controller类的方法,表示该方法是一个ApiOperation,即API的一个操作。该注解包含以下属性:
- value:ApiOperation的简要说明。
- notes:ApiOperation的详细说明。
- tags:指定API所属的标签,可以在Swagger UI中进行分类展示。
- response:设置API的响应类型,可以使用Java类或者Swagger定义的ResponseMessage类。
-
@ApiParam:用于标注Controller类的方法参数,表示该参数是一个API参数。该注解包含以下属性:
- value:API参数的简要说明。
- required:指定该参数是否必须。
- defaultValue:指定该参数的默认值。
-
@ApiModelProperty:用于标注Java类的属性,表示该属性是一个API参数或者响应参数。该注解包含以下属性:
- value:API参数或者响应参数的简要说明。
- required:指定该参数是否必须。
- example:指定该参数的示例值。
-
@ApiModel:用于标注Java类,表示该类是一个Swagger模型。该注解包含以下属性:
- value:模型的名称。
- description:模型的描述信息。
-
@ApiImplicitParam:用于标注Controller类的方法,表示API的隐式参数。该注解包含以下属性:
- name:参数名称。
- value:参数说明。
- dataType:参数类型。
- paramType:参数传递方式(query、header、path、cookie)。
-
@ApiImplicitParams:用于标注Controller类的方法,可以标注多个@ApiImplicitParam注解,表示API的多个隐式参数。
SpringBoot3.x整合Kinfe4j
启动报错
Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2024-06-14T13:07:02.377+08:00 ERROR 12220 --- [demo-knife4j] [ main] o.s.boot.SpringApplication : Application run failedorg.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'documentationPluginsBootstrapper' defined in URL [jar:file:/E:/env/repo/io/springfox/springfox-spring-web/2.10.5/springfox-spring-web-2.10.5.jar!/springfox/documentation/spring/web/plugins/DocumentationPluginsBootstrapper.class]: Unsatisfied dependency expressed through constructor parameter 1: Error creating bean with name 'webMvcRequestHandlerProvider' defined in URL [jar:file:/E:/env/repo/io/springfox/springfox-spring-webmvc/2.10.5/springfox-spring-webmvc-2.10.5.jar!/springfox/documentation/spring/web/plugins/WebMvcRequestHandlerProvider.class]: Unexpected exception during bean creationat org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:795) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:237) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1357) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1194) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:562) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:337) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:335) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:975) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:962) ~[spring-context-6.1.8.jar:6.1.8]at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:624) ~[spring-context-6.1.8.jar:6.1.8]at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.3.0.jar:3.3.0]at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-3.3.0.jar:3.3.0]at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:456) ~[spring-boot-3.3.0.jar:3.3.0]at org.springframework.boot.SpringApplication.run(SpringApplication.java:335) ~[spring-boot-3.3.0.jar:3.3.0]at org.springframework.boot.SpringApplication.run(SpringApplication.java:1363) ~[spring-boot-3.3.0.jar:3.3.0]at org.springframework.boot.SpringApplication.run(SpringApplication.java:1352) ~[spring-boot-3.3.0.jar:3.3.0]at com.kgc.DemoKnife4jApplication.main(DemoKnife4jApplication.java:12) ~[classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webMvcRequestHandlerProvider' defined in URL [jar:file:/E:/env/repo/io/springfox/springfox-spring-webmvc/2.10.5/springfox-spring-webmvc-2.10.5.jar!/springfox/documentation/spring/web/plugins/WebMvcRequestHandlerProvider.class]: Unexpected exception during bean creationat org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:535) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:337) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:335) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:254) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1689) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1653) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeanCollection(DefaultListableBeanFactory.java:1543) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeans(DefaultListableBeanFactory.java:1511) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1392) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1353) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:904) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:782) ~[spring-beans-6.1.8.jar:6.1.8]... 19 common frames omitted
Caused by: java.lang.TypeNotPresentException: Type javax.servlet.ServletContext not presentat java.base/sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:117) ~[na:na]at java.base/sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:125) ~[na:na]at java.base/sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49) ~[na:na]at java.base/sun.reflect.generics.visitor.Reifier.reifyTypeArguments(Reifier.java:68) ~[na:na]at java.base/sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:138) ~[na:na]at java.base/sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49) ~[na:na]at java.base/sun.reflect.generics.repository.ConstructorRepository.computeParameterTypes(ConstructorRepository.java:111) ~[na:na]at java.base/sun.reflect.generics.repository.ConstructorRepository.getParameterTypes(ConstructorRepository.java:87) ~[na:na]at java.base/java.lang.reflect.Executable.getGenericParameterTypes(Executable.java:298) ~[na:na]at java.base/java.lang.reflect.Constructor.getGenericParameterTypes(Constructor.java:281) ~[na:na]at org.springframework.core.MethodParameter.getGenericParameterType(MethodParameter.java:519) ~[spring-core-6.1.8.jar:6.1.8]at org.springframework.core.MethodParameter.getNestedParameterType(MethodParameter.java:559) ~[spring-core-6.1.8.jar:6.1.8]at org.springframework.beans.factory.config.DependencyDescriptor.getDependencyType(DependencyDescriptor.java:374) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1368) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.DefaultListableBeanFactory.createOptionalDependency(DefaultListableBeanFactory.java:1930) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1337) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:904) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:782) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:237) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1357) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1194) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:562) ~[spring-beans-6.1.8.jar:6.1.8]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522) ~[spring-beans-6.1.8.jar:6.1.8]... 32 common frames omitted
Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletContextat java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641) ~[na:na]at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188) ~[na:na]at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520) ~[na:na]at java.base/java.lang.Class.forName0(Native Method) ~[na:na]at java.base/java.lang.Class.forName(Class.java:467) ~[na:na]at java.base/sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:114) ~[na:na]... 54 common frames omitted
解决
1.更换依赖
<dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId><version>4.0.0</version></dependency>
2.启动类
package com.kgc;import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@EnableKnife4j
public class DemoBoot3Knife4jApplication {public static void main(String[] args) {SpringApplication.run(DemoBoot3Knife4jApplication.class, args);}}
3.配置
server:port: 8080
# springdoc-openapi项目访问访问地址: http://127.0.0.1:8080/doc.html
springdoc:swagger-ui:path: /swagger-ui.html# path: 配置swagger-ui.html/UI界面的访问路径,默认为/swagger-ui.htmltags-sorter: alpha# tags-sorter: 接口文档中的tags排序规则,默认为alpha,可选值为alpha(按字母顺序排序)或as-is(按照在代码中定义的顺序排序)operations-sorter: alphaapi-docs:path: /v3/api-docs# path: 配置api-docs的访问路径,默认为/v3/api-docsgroup-configs:# group-configs: 配置分组信息- group: 'default'# group: 分组名称paths-to-match: '/**'# paths-to-match: 配置要匹配的路径,默认为/**packages-to-scan: com.kgc.controller# packages-to-scan: 配置要扫描的包的路径,直接配置为Controller类所在的包名即可# knife4j项目访问访问地址:http://127.0.0.1:8080/doc.html#/home
knife4j:enable: true# 设置为true以启用Knife4j增强功能,这将再应用程序中启用Knife4j UIsetting:# language: 设置Knife4j UI的语言,默认为zh_cn,可选值为zh_cn或enlanguage: zh_cn#开启生产环境屏蔽production: false#是否启用登录认证basic:enable: trueusername: admin # 自己设置一个password: 123456 # 自己设置一个
4.配置类
package com.kgc.config;import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** @author: zjl* @datetime: 2024/6/14*/@Configuration
public class Knife4jConfig {@Beanpublic OpenAPI customOpenAPI() {return new OpenAPI().info(new Info().title("Springboot3.x整合Knife4接口文档").version("1.0").description("Springboot3.x整合Knife4").termsOfService("zhoujl.blog.csdn.net").contact(new Contact().name("Susheng").url("zhoujl.blog.csdn.net").email("180xxxx8296@163.com")));}@Beanpublic GroupedOpenApi publicApi() {return GroupedOpenApi.builder().group("前端接口").pathsToMatch("/api/**").build();}@Beanpublic GroupedOpenApi adminApi() {return GroupedOpenApi.builder().group("后端接口").pathsToMatch("/admin/**").build();}}
5.参数实体类
package com.kgc.pojo;import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Data;/*** @author: zjl* @datetime: 2024/6/14*/
@Data
@Builder
@Schema(description = "用户信息")
public class SaveUserDTO {@Schema(description = "用户id",required = true)private Long id;@Schema(description = "用户账号",required = true)private String userCode;@Schema(description = "用户姓名",required = false)private String userName;@Schema(description = "用户密码",required = true)private String userPassword;@Schema(description = "用户角色",required = true)private int userRole;
}
6.接口
admin
package com.kgc.controller;import com.kgc.pojo.SaveUserDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Nullable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.*;/*** @author: zjl* @datetime: 2024/6/14* @desc: 复兴Java,我辈义不容辞*/
@RestController
@RequestMapping("/admin")
@Tag(name = "用户接口")
public class AdminController {@PostMapping("/save")@Operation(summary = "添加用户")public Map<String,Object> save(SaveUserDTO saveUserDTO){Map<String,Object> resultMap = new HashMap<>();return resultMap;}@Operation(summary = "获取用户详情")@GetMapping("/detail")public SaveUserDTO detail(@Parameter(description = "用户id",required = true) Long id){SaveUserDTO saveUserDTO = SaveUserDTO.builder().id(1L).userCode("admin").userName("系统管理员").build();return saveUserDTO;}//@Nullable标识参数非必传@Operation(summary = "获取用户列表")@GetMapping("/list")public List<SaveUserDTO> list(@Parameter(description = "关键字") @Nullable String keyWord,@Parameter(description = "用户角色") @Nullable Integer userRole){List<SaveUserDTO> saveUserDTOList = new ArrayList<>();saveUserDTOList.add(SaveUserDTO.builder().id(1L).userCode("admin").userName("系统管理员").build());return saveUserDTOList;}
}
访问
访问地址:http://127.0.0.1:8080/doc.html
api
package com.kgc.controller;import com.kgc.pojo.SaveUserDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Nullable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** @author: zjl* @datetime: 2024/6/14* @desc: 复兴Java,我辈义不容辞*/
@RestController
@RequestMapping("/api")
@Tag(name = "用户接口")
public class ApiController {@PostMapping("/save")@Operation(summary = "添加用户")public Map<String,Object> save(SaveUserDTO saveUserDTO){Map<String,Object> resultMap = new HashMap<>();return resultMap;}@Operation(summary = "获取用户详情")@GetMapping("/detail")public SaveUserDTO detail(@Parameter(description = "用户id",required = true) Long id){SaveUserDTO saveUserDTO = SaveUserDTO.builder().id(1L).userCode("admin").userName("系统管理员").build();return saveUserDTO;}//@Nullable标识参数非必传@Operation(summary = "获取用户列表")@GetMapping("/list")public List<SaveUserDTO> list(@Parameter(description = "关键字") @Nullable String keyWord,@Parameter(description = "用户角色") @Nullable Integer userRole){List<SaveUserDTO> saveUserDTOList = new ArrayList<>();saveUserDTOList.add(SaveUserDTO.builder().id(1L).userCode("admin").userName("系统管理员").build());return saveUserDTOList;}
}
访问
访问地址:http://127.0.0.1:8080/doc.html
各版本注解参照
swagger2 | OpenAPI 3 | 注解位置 |
---|---|---|
@Api | @Tag(name = “接口类描述”) | Controller 类上 |
@ApiOperation | @Operation(summary =“接口方法描述”) | Controller 方法上 |
@ApiImplicitParams | @Parameters | Controller 方法上 |
@ApiImplicitParam | @Parameter(description=“参数描述”) | Controller 方法上 @Parameters 里 |
@ApiParam | @Parameter(description=“参数描述”) | Controller 方法的参数上 |
@ApiIgnore | @Parameter(hidden = true) 或 @Operation(hidden = true) 或 @Hidden | - |
@ApiModel | @Schema | DTO类上 |
@ApiModelProperty | @Schema | DTO属性上 |