Spring Boot 3 集成 Knife4j

基础环境

text 复制代码
SpringBoot : 3.0.6
Java: jdk-17.0.5
Maven: 3.6.1

依赖

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.giser</groupId>
    <artifactId>gis-java-mp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>gis-java-mp</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
		<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-web</artifactId>
		</dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

		<!-- 多数据源配置 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.6.1</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-aop</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        
		<!-- 代码自动生成 start -->
		<dependency>
		    <groupId>com.baomidou</groupId>
		    <artifactId>mybatis-plus-generator</artifactId>
		    <version>3.5.3</version>
		</dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-freemarker</artifactId>
		    <version>3.1.5</version>
		</dependency>
		<!-- 代码自动生成 end -->
		
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>3.0.0</version>
        </dependency>
     
     	<!-- Spring Boot 3 集成 Knife4j start -->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
        </dependency>
		<!-- Spring Boot 3 集成 Knife4j end -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.10</version>
        </dependency>
  <!-- 
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
    -->
    </dependencies>

    <repositories>
        <repository>
            <id>nexus-maven</id>
            <name>nexus-maven</name>
            <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
        </repository>
    </repositories>

	<!-- Spring Boot 3 集成 Knife4j start -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.github.xiaoymin</groupId>
                <artifactId>knife4j-dependencies</artifactId>
                <version>4.3.0-SNAPSHOT</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
	<!-- Spring Boot 3 集成 Knife4j end -->
	
    <build>
        <finalName>gis-mp</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.giser.mp.Knife4jSpringBoot3DemoApplication</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

基础配置

yml 复制代码
server:
  port: 9999
  servlet:
    context-path: /
    encoding:
      charset: UTF-8
  
spring:
  datasource:
    params: useSSL=false&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=GMT%2B8
    dynamic:
      primary: master
      strict: false
      datasource:
        master:
          url: jdbc:mysql://ip:port/db_name?${spring.datasource.params}
          username: db_user
          password: db_pwd
        slave:
          url: jdbc:mysql://ip:port/db_name?${spring.datasource.params}
          username: db_user
          password: db_pwd
      hikari:
        max-lifetime: 20000
        connection-timeout: 10000
        idle-timeout: 3000000
        min-idle: 4
        max-pool-size: 12
#
  servlet:
    multipart:
      max-file-size: 100MB
      max-request-size: 100MB
  application:
    name: gis-java-mp
springdoc:
  swagger-ui:
    path: /swagger-ui.html
    tags-sorter: alpha
    #operations-sorter: order
  api-docs:
    path: /v3/api-docs
  group-configs:
    - group: 'default'
      paths-to-match: '/**'
      # 生成接口文档的所需扫描的包路径
      packages-to-scan: com.giser.boot.knife4j
  default-flat-param-object: true

knife4j:
  enable: true
  setting:
    language: zh_cn
  basic:
    enable: false
    username: abc
    password: 123

使用

配置Swagger

java 复制代码
package com.giser.mp.config;

import cn.hutool.core.util.RandomUtil;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springdoc.core.customizers.GlobalOpenApiCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class SwaggerConfig {
    /**
     * 根据@Tag 上的排序,写入x-order
     *
     * @return the global open api customizer
     */
    @Bean
    public GlobalOpenApiCustomizer orderGlobalOpenApiCustomizer() {
        return openApi -> {
            if (openApi.getTags()!=null){
                openApi.getTags().forEach(tag -> {
                    Map<String,Object> map=new HashMap<>();
                    map.put("x-order", RandomUtil.randomInt(0,100));
                    tag.setExtensions(map);
                });
            }
            if(openApi.getPaths()!=null){
                openApi.addExtension("x-test123","333");
                openApi.getPaths().addExtension("x-abb",RandomUtil.randomInt(1,100));
            }

        };
    }

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("XXX用户系统API")
                        .version("1.0")

                        .description( "Knife4j集成springdoc-openapi示例")
                        .termsOfService("http://doc.xiaominfo.com")
                        .license(new License().name("Apache 2.0")
                                .url("http://doc.xiaominfo.com")));
    }


}

启动注入

java 复制代码
package com.giser.mp;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@SpringBootApplication
@MapperScan("com.giser.mp.*.mapper")
public class Knife4jSpringBoot3DemoApplication {
	private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Knife4jSpringBoot3DemoApplication.class);

    @SneakyThrows
    public static void main(String[] args) throws UnknownHostException {
        SpringApplication app=new SpringApplication(Knife4jSpringBoot3DemoApplication.class);
        ConfigurableApplicationContext application=app.run(args);
        //ConfigurableApplicationContext application=SpringApplication.run(Knife4jSpringBootDemoApplication.class, args);
        Environment env = application.getEnvironment();
        log.info("\n----------------------------------------------------------\n\t" +
                        "Application '{}' is running! Access URLs:\n\t" +
                        "Local: \t\thttp://localhost:{}\n\t" +
                        "External: \thttp://{}:{}\n\t"+
                        "Doc: \thttp://{}:{}/doc.html\n"+
                        "----------------------------------------------------------",
                env.getProperty("spring.application.name"),
                env.getProperty("server.port"),
                InetAddress.getLocalHost().getHostAddress(),
                env.getProperty("server.port"),
                InetAddress.getLocalHost().getHostAddress(),
                env.getProperty("server.port"));
    }

}

应用

java 复制代码
package com.giser.mp.web;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;

@RestController
@RequestMapping("/api/demo/")
@Tag(name = "接口文档示例")
public class Body1Controller {

    @Operation(summary = "GET")
    @ApiOperationSupport(order = 10)
    @GetMapping("/user/{id}")
    public ResponseEntity<String> getDemo(@PathVariable("id") String id){
        return ResponseEntity.ok(null);
    }

    @Operation(summary = "POST")
    @ApiOperationSupport(order = 1)
    @PostMapping("/m1")
    public ResponseEntity<String> postDemo(@RequestBody String request){
        return ResponseEntity.ok(request);
    }
    
    @Operation(summary = "PUT")
    @ApiOperationSupport(order = 2)
    @PutMapping("/m12")
    public ResponseEntity<String> putDemo(@PathVariable("id") String id){
        return ResponseEntity.ok(id);
    }
    
    @Operation(summary = "DELETE")
    @ApiOperationSupport(order = 2)
    @DeleteMapping("/user/{id}")
    public ResponseEntity<String> deleteDemo(@PathVariable("id") String id){
        return ResponseEntity.ok(id);
    }
    
    @Operation(summary = "普通body请求")
    @PostMapping("/body")
    public ResponseEntity<Object> body(@RequestBody Object fileResp){
        return ResponseEntity.ok(fileResp);
    }

    @Operation(summary = "普通body请求+Param+Header+Path")
    @Parameters({
            @Parameter(name = "id",description = "文件id",in = ParameterIn.PATH),
            @Parameter(name = "token",description = "请求token",required = true,in = ParameterIn.HEADER),
            @Parameter(name = "name",description = "文件名称",required = true,in=ParameterIn.QUERY)
    })
    @PostMapping("/bodyParamHeaderPath/{id}")
    public ResponseEntity<Object> bodyParamHeaderPath(@PathVariable("id") String id,@RequestHeader("token") String token, @RequestParam("name")String name,@RequestBody Object fileResp){
        return ResponseEntity.ok(fileResp);
    }

}

参考 Knife4j

相关推荐
kiddkid8 分钟前
RabbitMQ高级
java·rabbitmq·java-rabbitmq
小张帅三代1 小时前
【spark-spring boot】学习笔记
spring boot·学习·spark
爱编程的小生1 小时前
Easyexcel(7-自定义样式)
java·excel
camellias_2 小时前
SpringBoot(三十九)SpringBoot集成RabbitMQ实现流量削峰添谷
spring boot·rabbitmq·java-rabbitmq
AI人H哥会Java2 小时前
【JAVA】Java基础—面向对象编程:常用API与数据结构—集合框架(List、Set、Map等)
java·开发语言
2301_793086872 小时前
springboot+redis+lua脚本实现滑动窗口限流
spring boot·redis·lua
一只爱撸猫的程序猿2 小时前
简单解决一个同城多活中的机房之间数据同步的问题
spring boot·mysql·kafka
神仙别闹2 小时前
基于C语言实现的(控制台)校园导航系统
java·服务器·c语言
轩情吖2 小时前
模拟实现Bash
linux·c语言·开发语言·c++·后端·bash·环境变量
路在脚下@3 小时前
Spring MVC
java·spring