• Spring Boot 3 集成 Knife4j


    基础环境

    SpringBoot : 3.0.6
    Java: jdk-17.0.5
    Maven: 3.6.1
    
    • 1
    • 2
    • 3

    依赖

    
    <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.0modelVersion>
        <parent>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-parentartifactId>
            <version>3.0.6version>
            <relativePath/> 
        parent>
        <groupId>com.gisergroupId>
        <artifactId>gis-java-mpartifactId>
        <version>0.0.1-SNAPSHOTversion>
        <name>gis-java-mpname>
        <description>Demo project for Spring Bootdescription>
        <properties>
            <java.version>17java.version>
        properties>
        <dependencies>
    		
    		<dependency>
    		    <groupId>org.springframework.bootgroupId>
    		    <artifactId>spring-boot-starter-webartifactId>
    		dependency>
    
            <dependency>
                <groupId>com.baomidougroupId>
                <artifactId>mybatis-plus-boot-starterartifactId>
                <version>3.5.3version>
                <exclusions>
                    <exclusion>
                        <groupId>org.springframework.bootgroupId>
                        <artifactId>spring-boot-starter-jdbcartifactId>
                    exclusion>
                exclusions>
            dependency>
    
    		
            <dependency>
                <groupId>com.baomidougroupId>
                <artifactId>dynamic-datasource-spring-boot-starterartifactId>
                <version>3.6.1version>
                <exclusions>
                    <exclusion>
                        <groupId>org.springframework.bootgroupId>
                        <artifactId>spring-boot-starter-aopartifactId>
                    exclusion>
                    <exclusion>
                        <groupId>org.springframework.bootgroupId>
                        <artifactId>spring-boot-starter-jdbcartifactId>
                    exclusion>
                exclusions>
            dependency>
            
    		
    		<dependency>
    		    <groupId>com.baomidougroupId>
    		    <artifactId>mybatis-plus-generatorartifactId>
    		    <version>3.5.3version>
    		dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-jdbcartifactId>
                <version>2.1.3.RELEASEversion>
            dependency>
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>8.0.16version>
            dependency>
    		<dependency>
    		    <groupId>org.springframework.bootgroupId>
    		    <artifactId>spring-boot-starter-freemarkerartifactId>
    		    <version>3.1.5version>
    		dependency>
    		
    		
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
                <version>1.18.24version>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-testartifactId>
                <scope>testscope>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-autoconfigureartifactId>
                <version>3.0.0version>
            dependency>
         
         	
            <dependency>
                <groupId>com.github.xiaoymingroupId>
                <artifactId>knife4j-openapi3-jakarta-spring-boot-starterartifactId>
            dependency>
    		
            <dependency>
                <groupId>cn.hutoolgroupId>
                <artifactId>hutool-allartifactId>
                <version>5.8.10version>
            dependency>
      
        dependencies>
    
        <repositories>
            <repository>
                <id>nexus-mavenid>
                <name>nexus-mavenname>
                <url>https://oss.sonatype.org/content/repositories/snapshots/url>
            repository>
        repositories>
    
    	
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>com.github.xiaoymingroupId>
                    <artifactId>knife4j-dependenciesartifactId>
                    <version>4.3.0-SNAPSHOTversion>
                    <type>pomtype>
                    <scope>importscope>
                dependency>
            dependencies>
        dependencyManagement>
    	
    	
        <build>
            <finalName>gis-mpfinalName>
            <plugins>
                <plugin>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-maven-pluginartifactId>
                    <configuration>
                        <mainClass>com.giser.mp.Knife4jSpringBoot3DemoApplicationmainClass>
                    configuration>
                plugin>
            plugins>
        build>
    
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148

    基础配置

    
    
    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.mp
      default-flat-param-object: true
    
    knife4j:
      enable: true
      setting:
        language: zh_cn
      basic:
        enable: false
        username: abc
        password: 123
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59

    使用

    配置Swagger

    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")));
        }
    
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53

    启动注入

    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"));
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    应用

    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);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73

    参考 Knife4j

  • 相关阅读:
    【解决】多卡服务器GPU不能多用户同时使用的问题
    ChatGPT原理简介
    无线传感器网络:网络层
    IOS17正式版今日发布
    [附源码]Python计算机毕业设计Django的酒店预订系统设计与实现
    Qt ffmpeg音视频转换工具
    数据结构与算法之矩阵: Leetcode 134. 螺旋矩阵 (Typescript版)
    JAVA Exception in thread “main“ java.lang.NullPointerException
    《线性代数》科教版教材必会习题
    Authing 入选 Gartner《2022 中国网络安全技术成熟度曲线》报告
  • 原文地址:https://blog.csdn.net/SUNBOYmxbsH/article/details/134553466