### Disk Mode Example Configuration: Comprehensive Setup Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/gitee/docs/middleware-sources/desktop-test.html An example configuration for Disk mode demonstrating a comprehensive setup including service name, host, location, service path, and basic authentication. This serves as a reference for setting up multiple services. ```properties knife4j.disk.routes[0].name=测试平台 knife4j.disk.routes[0].host=http://knife4j.xiaominfo.com knife4j.disk.routes[0].location=test.json knife4j.disk.routes[0].servicePath=/niubiaknife4j.disk.routes[1].name=用户体系 knife4j.disk.routes[1].host=http://knife4j.xiaominfo.com knife4j.disk.routes[1].location=user.json#knife4j.basicAuth.enable=true#knife4j.basicAuth.username=zhangsan#knife4j.basicAuth.password=123456 ``` -------------------------------- ### Install Dependencies Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/community/contributing.mdx Run this command to install the necessary dependencies for the frontend project. ```bash npm install ``` -------------------------------- ### Start Nginx Manually Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/solution/knife4j-admin-deploy.md If Nginx is not installed as a system service, start it manually from its installation directory. ```shell [root@izbt kadmin]# cd /usr/local/nginx [root@izbt nginx]# sbin/nginx ``` -------------------------------- ### Start Method in DocumentationPluginsBootstrapper Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/action/springfox/springfox7.md The start() method iterates through discovered DocumentationPlugin instances (typically Docket beans), sorts them, and initiates the documentation scanning process for enabled plugins. ```java @Override public void start() { if (initialized.compareAndSet(false, true)) { log.info("Context refreshed"); //此处拿到DocumentationPlugin插件 //因为Docket类是实现了DocumentationPlugin,我们在程序外部通过@Bean注解注入到Spring容器中,所以此处DocumentationPlugin的实例对象是Docket对象 //一个Docket代表的一个分组,多个则是多个文档分组 //调用guava的排序规则,根据groupName排序 //思考:在重构Swagger-ui的过程中,会有需求能否提供默认的排序规则,因为groupName排序对用户来说太死板,可以提供一个order参数值来进行默认排序,这样对用户更友好 List plugins = pluginOrdering() .sortedCopy(documentationPluginsManager.documentationPlugins()); log.info("Found {} custom documentation plugin(s)", plugins.size()); //遍历Docket对象 for (DocumentationPlugin each : plugins) { //获取文档类型,一般都是Swagger_2 DocumentationType documentationType = each.getDocumentationType(); if (each.isEnabled()) { //如果启用,则开始扫描生成文档 scanDocumentation(buildContext(each)); } else { log.info("Skipping initializing disabled plugin bean {} v{}", documentationType.getName(), documentationType.getVersion()); } } } } ``` -------------------------------- ### Add Guide Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j/exportWord.html Adds a new guide by providing guide attributes. This endpoint allows for the creation of new guide entries in the system. ```APIDOC ## Add Guide ### Description Adds a new guide by providing guide attributes. This endpoint allows for the creation of new guide entries in the system. ### Method GET ### Endpoint /api/guide/add ### Parameters #### Query Parameters - **name** (string) - Optional - Name of the guide. - **email** (string) - Optional - Email of the guide. - **id** (string) - Optional - The primary key ID of the guide. ### Request Example ```json { "name": "张飞", "code": 8200, "message": "成功", "success": true } ``` ### Response #### Success Response (200) - **OK** (Rest«Knife4jUser») - OK #### Response Example ```json { "name": "张飞", "code": 8200, "message": null, "success": true } ``` ``` -------------------------------- ### Add Guide Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j/exportWord1.html Adds a new guide by providing guide attributes. This endpoint accepts guide information in JSON format and returns a response indicating the success of the operation. ```APIDOC ## GET /api/guide/add ### Description Adds a new guide by providing guide attributes. ### Method GET ### Endpoint /api/guide/add ### Parameters #### Query Parameters - **name** (string) - Optional - Name of the guide. - **email** (string) - Optional - Email of the guide. - **id** (string) - Optional - The unique identifier for the guide. ### Request Example ```json { "name": "张飞", "code": 8200, "message": "成功", "success": true } ``` ### Response #### Success Response (200) - **name** (string) - The name of the guide. - **code** (integer) - The status code of the response. - **message** (string) - The message associated with the response. - **success** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "name": "张飞", "code": 8200, "message": null, "success": true } ``` ``` -------------------------------- ### Springdoc OpenAPI Starter Deployment Guide Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/faq/nginx-forward-path.md Official documentation link for deploying springdoc-openapi-starter behind a reverse proxy. ```http https://springdoc.org/#how-can-i-deploy-springdoc-openapi-starter-webmvc-ui-behind-a-reverse-proxy ``` -------------------------------- ### Start Nginx Service Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/solution/knife4j-admin-deploy.md Start the Nginx service using the system's service management command. ```shell [root@izbt kadmin]# service nginx start ``` -------------------------------- ### Manual Routes Configuration Example Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/blog/gateway/knife4j-gateway-introduce.mdx Example of manually configuring custom routes for Knife4j Gateway aggregation. This configuration is directly used as a data source for aggregation. ```yaml knife4j: gateway: enabled: true # 选择手动 strategy: manual routes: - name: 用户服务 service-name: user-service url: /user/v2/api-docs ``` -------------------------------- ### Start Knife4j Admin Service Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/solution/knife4j-admin-deploy.md Initiate the Knife4j Admin service using its startup script from the terminal. ```shell [root@izbt kadmin]# ./startup.sh ``` -------------------------------- ### Start Knife4j Admin Application Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/solution/knife4j-admin-deploy.md Execute the `startup.sh` script to launch the Knife4j Admin Spring Boot JAR in the background. ```shell nohup java -Xms512m -Xmx512m -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=256m -XX:MaxNewSize=256m -jar /mnt/application/kadmin/knife4j-admin-1.0.jar >> /dev/null 2>&1 & ``` -------------------------------- ### Nacos Configuration Example Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/gitee/docs/middleware-sources/desktop/config-disk.html Example configuration for Knife4j in Nacos mode. This should be placed in a nacos.properties file within your project's data directory. ```properties knife4j.nacos[0].server=127.0.0.1:8848 knife4j.nacos[0].username=nacos knife4j.nacos[0].password=nacos knife4j.nacos[0].namespace=dev knife4j.nacos[0].routes[0].name=用户 knife4j.nacos[0].routes[0].serviceName=userService knife4j.nacos[0].routes[0].groupName=DEFAULT_GROUP knife4j.nacos[0].routes[0].location=/v2/api-docs?group=2.X版本 ``` -------------------------------- ### Cloud Mode Configuration: Basic Setup Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/gitee/docs/middleware-sources/desktop-test.html Configure basic service name, location, and URI for services in Cloud mode. This enables aggregation of API documentation from multiple microservices. ```properties knife4j.cloud.routes[0].name=大数据平台1 knife4j.cloud.routes[0].location=/v2/api-docs?group=3.默认接口 knife4j.cloud.routes[0].uri=http://knife4j.xiaominfo.com knife4j.cloud.routes[1].name=甄选平台 knife4j.cloud.routes[1].location=/v2/api-docs?group=2.X版本 knife4j.cloud.routes[1].uri=http://knife4j.xiaominfo.com ``` -------------------------------- ### Check Java Version Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/solution/knife4j-admin-deploy.md Verify the installed Java version on the server. This is a prerequisite for running the Java application. ```shell [root@iZbt ~]# java -version java version "1.8.0_144" Java(TM) SE Runtime Environment (build 1.8.0_144-b01) Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode) ``` -------------------------------- ### DocumentationPluginsBootstrapper Class Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/action/springfox/springfox7.md The DocumentationPluginsBootstrapper class implements Spring's SmartLifecycle interface, ensuring its start() method is called after the application context is refreshed. It manages the initialization of documentation plugins. ```java /** * After an application context refresh, builds and executes all DocumentationConfigurer instances found in the * application context. * * If no instances DocumentationConfigurer are found a default one is created and executed. */ @Component public class DocumentationPluginsBootstrapper implements SmartLifecycle { private static final Logger log = LoggerFactory.getLogger(DocumentationPluginsBootstrapper.class); private static final String SPRINGFOX_DOCUMENTATION_AUTO_STARTUP = "springfox.documentation.auto-startup"; //插件管理类,提供了一些列的Swagger相关参数的插件 private final DocumentationPluginsManager documentationPluginsManager; //所有的请求接口结果 /*** * springfox.documentation.spring.web.plugins */ private final List handlerProviders; } ``` -------------------------------- ### Basic Gateway Aggregation Configuration Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/blog/gateway/knife4j-gateway-introduce.mdx Configure Knife4j-gateway to enable aggregation using the discover strategy. This setup automatically aggregates documentation from discovered services. ```yaml knife4j: gateway: # ① 第一个配置,开启gateway聚合组件 enabled: true # ② 第二行配置,设置聚合模式采用discover服务发现的模式 strategy: discover discover: # ③ 第三行配置,开启discover模式 enabled: true # ④ 第四行配置,聚合子服务全部为Swagger2规范的文档 version: swagger2 ``` -------------------------------- ### Gateway Aggregation with Excluded Services Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/changelog/4.x/4.3.md Configure gateway aggregation to exclude specific services using regular expressions. This example excludes services whose names start with 'order'. ```yaml knife4j: gateway: enabled: true strategy: discover discover: version: swagger2 enabled: true excluded-services: # 排除order开头的配置 - order.* ``` -------------------------------- ### Algolia Crawler Configuration Example Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/action/others/doc-search.md This JSON configuration defines the parameters for the Algolia web crawler. It specifies the index name, starting URLs for crawling, and CSS selectors to extract content from web pages. ```json { "index_name": "knife4j", "start_urls": [ "https://doc.xiaominfo.com/docs/middleware-sources", "https://doc.xiaominfo.com/docs/oas", "https://doc.xiaominfo.com/docs/action", "https://doc.xiaominfo.com/docs/changelog", "https://doc.xiaominfo.com/docs/faq", "https://doc.xiaominfo.com/v2/" ], "selectors": { "lvl0": ".docMainContainer_gTbr header h1", "lvl1": ".docMainContainer_gTbr article h1", "lvl2": ".docMainContainer_gTbr article h2", "lvl3": ".docMainContainer_gTbr article h3", "lvl4": ".docMainContainer_gTbr article h4", "lvl5": ".docMainContainer_gTbr article h5", "text": ".docMainContainer_gTbr header p,.docMainContainer_gTbr section p,.docMainContainer_gTbr section ol" } } ``` -------------------------------- ### Springfox Initialization Logic in start() Method Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/gitee/docs/action/springfox/springfox7.html This method is executed when the Spring application context is initialized. It retrieves and sorts `DocumentationPlugin` instances (typically `Docket` beans) and initiates the documentation scanning process for enabled plugins. ```java @Override public void start() { if (initialized.compareAndSet(false, true)) { log.info("Context refreshed"); //此处拿到DocumentationPlugin插件 //因为Docket类是实现了DocumentationPlugin,我们在程序外部通过@Bean注解注入到Spring容器中,所以此处DocumentationPlugin的实例对象是Docket对象 //一个Docket代表的一个分组,多个则是多个文档分组 //调用guava的排序规则,根据groupName排序 //思考:在重构Swagger-ui的过程中,会有需求能否提供默认的排序规则,因为groupName排序对用户来说太死板,可以提供一个order参数值来进行默认排序,这样对用户更友好 List plugins = pluginOrdering() .sortedCopy(documentationPluginsManager.documentationPlugins()); log.info("Found {} custom documentation plugin(s)", plugins.size()); //遍历Docket对象 for (DocumentationPlugin each : plugins) { //获取文档类型,一般都是Swagger_2 DocumentationType documentationType = each.getDocumentationType(); if (each.isEnabled()) { //如果启用,则开始扫描生成文档 scanDocumentation(buildContext(each)); } else { log.info("Skipping initializing disabled plugin bean {} v{}", documentationType.getName(), documentationType.getVersion()); } } } } ``` -------------------------------- ### Knife4jAggregationDesktop Configuration Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/gitee/docs/middleware/knife4jAggregationDesktop.html Configure the startup port, and optionally enable BasicAuth for all OpenAPI documents or specific project documents. ```properties # Knife4jAggregationDesktop 启动端口号 knife4j.port=18006 # 为所有Knife4jAggregationDesktop开放出去的OpenAPI文档加权,设置BasicAuth访问密码 # enable=true 代表启用 knife4j.basic.enable=true knife4j.basic.username=zhangsanknife4j.basic.password=123456 # 使用者也可以为单个开放出去的OpenAPI文档独立设置Basic验证权限,设置规则是knife4j.basic.项目code.开头 # 例如一个项目文档的访问路径是:http://localhost:18006/bigdata/doc.html,那么bigdata就是该项目的code,为该文档设置BasicAuth knife4j.basic.bigdata.enable=true knife4j.basic.bigdata.username=zhangsanknife4j.basic.bigdata.password=123456 ``` -------------------------------- ### Delete Guide Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j/exportWord1.html Deletes a guide. This endpoint is designed to remove guide information from the system. ```APIDOC ## DELETE /api/guide/add ### Description Deletes a guide by providing guide attributes. This endpoint accepts guide information in JSON format and returns a response indicating the success of the operation. ### Method DELETE ### Endpoint /api/guide/add ### Request Example ```json { "data": "", "errCode": 0, "message": "", "success": true } ``` ### Response #### Success Response (200) - **data** (string) - The data returned in the response. - **errCode** (integer) - The error code. - **message** (string) - The message associated with the response. - **success** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "data": "", "errCode": 0, "message": "", "success": true } ``` ``` -------------------------------- ### Disk Mode Configuration: Basic Setup Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/gitee/docs/middleware-sources/desktop-test.html Configure basic service name, host, and location for a static JSON OpenAPI specification file in Disk mode. This enables rendering and debugging. ```properties knife4j.disk.routes[0].name=测试平台 knife4j.disk.routes[0].host=http://knife4j.xiaominfo.com knife4j.disk.routes[0].location=test.json ``` -------------------------------- ### Delete Guide Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j/exportWord.html Deletes a guide. This endpoint is used to remove existing guide entries from the system. ```APIDOC ## Delete Guide ### Description Deletes a guide. This endpoint is used to remove existing guide entries from the system. ### Method DELETE ### Endpoint /api/guide/add ### Request Example ```json {"data": "","errCode": 0,"message": "","success": true} ``` ### Response Example ```json {"data": "","errCode": 0,"message": "","success": true} ``` ``` -------------------------------- ### Initialize Default Configuration Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/gitee/docs/action/springfox/springfox8.html This code snippet shows the instantiation of DefaultConfiguration within the DocumentationPluginsBootstrapper constructor, passing necessary dependencies like Defaults, TypeResolver, and ServletContext. ```java //通过DefaultConfiguration可以构建DocumentationContextBuilder this.defaultConfiguration = new DefaultConfiguration(defaults, typeResolver, servletContext); ``` -------------------------------- ### Incorrect Use of @ApiModelProperty Example for Generic Type Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/gitee/docs/faq/swagger-des-not-found.html Do not assign an 'example' value to @ApiModelProperty for a generic type T within a wrapper class. This can cause inconsistent example values in the generated documentation, as T's actual type is determined at runtime. ```java public class Rest { /* * 泛型T属性不能赋予example值,因为T有可能是实体类,这样赋值会导致生成的示例值不一致,应该交给框架去解析类结构 */ @ApiModelProperty(value = "返回对象",example="Test") private T data; } ``` -------------------------------- ### Simulation of Mobile Top-up with Spring Context Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/gitee/docs/action/springfox/springfox3.html Demonstrates how to simulate the mobile top-up process using Spring's AnnotationConfigApplicationContext. It loads the application context and calls the CustomerService to perform a top-up. ```java public class MobileTest { public static void main(String[] args) { AnnotationConfigApplicationContext context= new AnnotationConfigApplicationContext("com.xiaominfo.cloud.plugin.phone"); CustomerService customerService=context.getBean(CustomerService.class); MobileCustomer mobileCustomer=new MobileCustomer("13567662664"); mobileCustomer.setOld(true); customerService.increments(mobileCustomer,120); } } ``` -------------------------------- ### Java Version Check Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/gitee/docs/solution/knife4j-admin-deploy.html Verifies the installed Java version on the system. Ensure Java 8 or higher is installed. ```bash java -version ``` -------------------------------- ### Example Swagger JSON Content Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/solution/ui-front-static.md An example of the content expected in a static swagger.json file. This structure follows the Swagger 2.0 specification. ```json { "swagger": "2.0", "info": { "description": "
swagger-bootstrap-ui-demo RESTful APIs
", "version": "1.0", "title": "swagger-bootstrap-ui很棒~~~!!!", "termsOfService": "http://www.group.com/", "contact": { "name": "group@qq.com" } }, "host": "127.0.0.1:8999", "basePath": "/" //more..... } ``` -------------------------------- ### Get Request with ParameterObject Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/gitee/docs/faq/v4/knife4j-parameterobject-flat-param.html Demonstrates a GET request endpoint where the DTO is annotated with @ParameterObject to ensure it's parsed as a flat parameter. ```java @Operation(summary = "Get 请求", tags = "对接口分组", description = "对接口的作用进行描述") @RequestMapping(value = "/api/v1/open-api", method = RequestMethod.GET) public R get(@ParameterObject GetDTO dto) { return R.ok(dto); } ``` -------------------------------- ### Spring Boot Monolithic Architecture Starter Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j/README.md This starter is for Spring Boot monolithic architectures using OpenAPI2. It includes all Knife4j resources, including the frontend UI. ```xml com.github.xiaoymin knife4j-openapi2-spring-boot-starter ${knife4j.version} ``` -------------------------------- ### Original Get Request Endpoint Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/faq/v4/knife4j-parameterobject-flat-param.md This is the original Java code for a GET request endpoint before applying any Knife4j v4.0 parameter resolution solutions. ```java @Operation(summary = "Get 请求", tags = "对接口分组", description = "对接口的作用进行描述") @RequestMapping(value = "/api/v1/open-api", method = RequestMethod.GET) public R get(GetDTO dto) { return R.ok(dto); } ``` -------------------------------- ### Spring Boot Application Startup Configuration Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/action/springcloud-gateway.md Main application class for the documentation service. It enables discovery client and Eureka client, and runs the Spring Boot application. ```java @EnableDiscoveryClient @EnableEurekaClient @SpringBootApplication public class ServiceDocApplication { public static void main(String[] args) { SpringApplication.run(ServiceDocApplication.class, args); } } ``` -------------------------------- ### Enable Custom Home Page Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/features/customHome.md Configure application properties to enable custom home page content. Ensure Knife4j is enabled. ```yaml knife4j: enable: true setting: enable-home-custom: true # 自4.1.0版本开始,该属性过时,请使用下面home-custom-path属性 home-custom-location: classpath:markdown/home.md # 自4.1.0版本开始,替代home-custom-location属性,开发者请使用该配置 home-custom-path: classpath:markdown/home.md ``` -------------------------------- ### Java Entity with Example Value Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/gitee/docs/features/requestCache.html This Java entity demonstrates how providing an 'example' value for a property in Swagger annotations prevents Knife4j from using cached debug values. ```java public class SwaggerRequestBody{ @ApiModelProperty(value="姓名",example="张飞") private String name; //more... } ``` -------------------------------- ### Include Knife4j Starter in Spring Boot Project Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/action/mavenbom.md After importing the BOM, include the `knife4j-spring-boot-starter` dependency in your Spring Boot project's `dependencies` section. The version will be managed by the imported BOM. ```xml com.github.xiaoymin knife4j-spring-boot-starter ``` -------------------------------- ### Java Entity without Example Value Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/gitee/docs/features/requestCache.html This Java entity shows a property without an 'example' value. In this case, Knife4j will cache the value provided during debugging for subsequent requests. ```java public class SwaggerRequestBody{ @ApiModelProperty(value="姓名") private String name; //more... } ``` -------------------------------- ### DocumentationPluginsBootstrapper 源码 Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/gitee/docs/action/springfox/springfox7.html 展示了 `DocumentationPluginsBootstrapper.java` 的部分核心源码,这是 Springfox 文档初始化的起点。 ```java package springfox.documentation.spring.web.plugins; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; import springfox.documentation.spi.service.DocumentationPlugin; import springfox.documentation.spi.service.DocumentationPluginsManager; import java.util.Set; /** * DocumentationPluginsBootstrapper.java * @author: * @since: */ @Component public class DocumentationPluginsBootstrapper implements ApplicationListener { private final DocumentationPluginsManager documentationPluginsManager; private final Set documentationPlugins; private boolean initialised = false; @Autowired public DocumentationPluginsBootstrapper(DocumentationPluginsManager documentationPluginsManager, Set documentationPlugins) { this.documentationPluginsManager = documentationPluginsManager; this.documentationPlugins = documentationPlugins; } @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { if (!initialised) { documentationPluginsManager.register(documentationPlugins); initialised = true; } } } ``` -------------------------------- ### Get Request Endpoint with @ParameterObject Annotation Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/faq/v4/knife4j-parameterobject-flat-param.md This Java code demonstrates how to resolve parameter object resolution issues in Knife4j v4.0 by adding the @ParameterObject annotation to the DTO parameter in the GET request endpoint. ```java @Operation(summary = "Get 请求", tags = "对接口分组", description = "对接口的作用进行描述") @RequestMapping(value = "/api/v1/open-api", method = RequestMethod.GET) public R get(@ParameterObject GetDTO dto) { return R.ok(dto); } ``` -------------------------------- ### Java Model with Invalid JSON Example Property Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/faq/knife4j-exception.md Illustrates a common cause of invalid JSON responses where the `example` attribute in `@ApiModelProperty` for a List attribute contains malformed JSON. This can lead to `JSON.parse()` failures in the frontend. ```java @ApiModel(description = "客户字段分组模型",value = "CrmFieldGroupResponse") public class CrmFieldGroupResponse { @ApiModelProperty(value = "客户字段分组ID") private int id; @ApiModelProperty(value = "客户字段分组名称") private String name; @ApiModelProperty(value = "客户字段数据",example = "{'id':'xxx'}") private List fields; } ``` -------------------------------- ### Application Directory Structure Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/solution/knife4j-admin-deploy.md Illustrates the expected file and directory structure for the Knife4j Admin deployment. ```shell |-kadmin |----data //数据目录,可以为空,在部署时该目录必须先手工创建 |----front //由zip包解压得到 |----logs //程序的日志目录,在部署时该目录必须先手工创建 |----startup.sh //启动脚本,必须使用chmod+x startup.sh 命令赋予可执行权限 |----knife4j-admin-1.0.jar //由zip包解压得到 ``` -------------------------------- ### Knife4j Gateway Detailed Configuration Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j/knife4j-gateway-spring-boot-starter/README.md A comprehensive configuration example for Knife4j gateway, covering enabled status, API path prefix, UI version, service discovery settings, and route definitions for different microservices. ```yaml knife4j: gateway: # 开区网关聚合文档 默认:/ enabled: true # 网关前缀(如nginx配置的代理前缀) 默认:/ api-path-prefix: /api # 使用的UI版本(v2或者v3) 默认: v3 version: v2 # 服务发现 discover: # 开启服务发现 默认:true enabled: true # 默认排序 默认:0 default-order: 0 # 排除的服务名 默认:为空(建议排除网关服务) excluded-services: order-server,user-server v2: # 文档访问地址 默认:/v2/api-docs?group=default api-docs-path: '/v2/api-docs?group=default' v3: # 文档访问地址 默认:/v3/api-docs api-docs-path: '/v3/api-docs' # oauth2 redirect url oauth2-redirect-url: '' # validator url validator-url: '' routes: # 分组名称 - name: mall-server # 文档地址 url: '/v2/api-docs' # context-path context-path: '/' # 服务名 service-name: mall-server # 排序 order: 1 ``` -------------------------------- ### Corrected Java Model Removing Example Property Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/faq/knife4j-exception.md Shows the corrected Java model where the `example` attribute is removed from the `@ApiModelProperty` for the List attribute. This allows `springfox-swagger2` to correctly generate the JSON schema, preventing parsing errors. ```java @ApiModel(description = "客户字段分组模型",value = "CrmFieldGroupResponse") public class CrmFieldGroupResponse { @ApiModelProperty(value = "客户字段分组ID") private int id; @ApiModelProperty(value = "客户字段分组名称") private String name; @ApiModelProperty(value = "客户字段数据") private List fields; } ``` -------------------------------- ### Configure Static Files and Swagger UI Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/gitee/docs/action/dotnetcore-knife4j-how.html This snippet shows how to enable static file serving and configure Swagger UI to use a custom index.html for the Knife4j UI. Ensure the 'wwwroot' directory contains the bundled UI files. ```csharp app.UseStaticFiles(); app.UseSwaggerUI(c =>{ c.RoutePrefix = ""; // serve the UI at root c.SwaggerEndpoint("/v1/api-docs", "V1 Docs");//This configuration is invalid. c.IndexStream = () => new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")).GetFileInfo("index.html").CreateReadStream(); }); ``` -------------------------------- ### Knife4j for OpenAPI2 (v4.0+) Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/quick-start/start-knife4j-version.mdx Starting from version 4.0, use `knife4j-openapi2-spring-boot-starter` for OpenAPI2 (Swagger2) specification compatibility. ```xml com.github.xiaoymin knife4j-openapi2-spring-boot-starter {maven仓库最新版本} ``` -------------------------------- ### Build Maven Project with Production Profile Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/blog/production-forbidden-ui.mdx Execute the Maven clean package command with the -Pprod flag to activate the production profile and exclude the specified UI JARs. ```shell mvn clean package -Pprod ``` -------------------------------- ### Frontend Initialization Logic Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/community/contributing.mdx This JavaScript code snippet shows how to initialize either the Springdoc OpenAPI or Springfox framework in the frontend. Choose one method and comment out the other. ```javascript created() { // 调试springdoc框架时,使用该方法,注释下面的this.initKnife4jSpringUi()方法 this.initSpringDocOpenApi(); // 调试springfox框架时,使用该方法,注释上面的 this.initSpringDocOpenApi()方法 //this.initKnife4jSpringUi(); this.initI18n(); } ``` -------------------------------- ### Create Documentation Context Builder Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/gitee/docs/action/springfox/springfox8.html This method is responsible for creating the initial DocumentationContextBuilder instance, applying resource grouping strategies based on the documentation type. ```java public DocumentationContextBuilder createContextBuilder( DocumentationType documentationType, DefaultConfiguration defaultConfiguration) { return defaultsProviders.getPluginFor(documentationType, defaultConfiguration) .create(documentationType) .withResourceGroupingStrategy(resourceGroupingStrategy(documentationType)); } ``` -------------------------------- ### Enable Knife4j Enhancement Source: https://github.com/xiaoymin/knife4j/blob/dev/knife4j-doc/docs/features/tagSort.md To enable enhanced features, configure the yml file. This is required starting from version 2.0.7. ```yaml knife4j: enable: true ```