Spring Boot 3 集成 Knife4j

基础环境

SpringBoot : 3.0.6
Java: jdk-17.0.5
Maven: 3.6.1

依赖


<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>

基础配置



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

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")));
    }


}

启动注入

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"));
    }

}

应用

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

你可能感兴趣的:(后端技术,#,SpringBoot,spring,boot,后端,java)