spring boot3 集成swagger3

快速开始 | Knife14j  官方的推荐

1. 设置pom.xml  主要是引入nexus-maven,com.github.xiaoymin 2个,cn.hutool,org.springframework



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        3.1.1
        

    
    com.lzp
    demo
    0.0.1-SNAPSHOT
    demo
    demo
    
        17
    
    
        
            nexus-maven
            nexus-maven
            https://oss.sonatype.org/content/repositories/snapshots/
        
    
    
        
            
                com.github.xiaoymin
                knife4j-dependencies
                4.2.0-SNAPSHOT
                pom
                import
            
        
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            3.0.2
        

        
            com.mysql
            mysql-connector-j
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter-test
            3.0.2
            test
        
        
            com.baomidou
            mybatis-plus-extension
            3.5.3.1
        
        
            org.projectlombok
            lombok
            1.18.28
        
        

        
            com.github.xiaoymin
            knife4j-openapi3-jakarta-spring-boot-starter
        
        
            cn.hutool
            hutool-all
            5.8.10
        
        
            org.springframework
            spring-tx
            5.2.2.RELEASE
        
        



    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
        
        
        
        
    


2. 随意位置创建 SwaggerConfig

package com.lzp.demo.utils;


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;
import java.util.*;

/**
 * @Descrpition
 * @Author  [email protected]
 * @Date 2022/6/15 20:22
 */
@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 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")));
    }


}

3. 修改 DemoApplication

package com.lzp.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import java.net.InetAddress;

@Slf4j
@SpringBootApplication
@MapperScan("com.lzp.demo.mapper")
public class DemoApplication  {
//    public static void main(String[] args) {
//        SpringApplication.run(DemoApplication.class, args);
//    }

    @SneakyThrows
    public static void main(String[] args) {
        SpringApplication app=new SpringApplication(DemoApplication.class);
        ConfigurableApplicationContext application=app.run(args);
//        ConfigurableApplicationContext application=SpringApplication.run(DemoApplication.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"));
    }
}

4. 修改application.yml 并在resources文件夹下创建markdown 和markdown1

spring boot3 集成swagger3_第1张图片

 

# 本服务
server:
  port: 8081
  servlet:
    context-path:

# 数据库配置
spring:
  servlet:
    multipart:
      max-file-size: 100MB
      max-request-size: 100MB
  application:
    name: com.lzp.demo
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/demo?characterEncoding=utf-8
    username: mydemo
    password: 123456
# 接口插件配置
mybatis:
     #标注待解析的mapper的xml文件位置
    mapper-locations: classpath:mapper/*.xml


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.lzp.demo
  default-flat-param-object: true

knife4j:
  enable: true
  setting:
    language: zh_cn
    swagger-model-name: 实体类列表
  documents:
    - name: 标题1
      locations: classpath:markdown/*
      group: default
    - name: 标题2
      locations: classpath:markdown1/*
      group: 用户模块
  basic:
    enable: false
    username: abc
    password: 123

5. 给控制文件添加对应注解

package com.lzp.demo.controller;

import com.lzp.demo.entity.Student;
import com.lzp.demo.service.StudentService;


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;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;

@Tag(name = "学生会")
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    StudentService studentService;


    @Operation(summary = "查询全部学生")
    @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)
    })
    @GetMapping("/getonename")
    List getOne(){
        return studentService.getOneName();
    }

    @Operation(summary = "增加一个学生")
    @PostMapping("/insertone")
    int insertone(Student student){
        return studentService.insertOne(student);
    }

    @Operation(summary = "删除一个学生")
    @DeleteMapping("/deleteone")
    int deleteone(String name){
        return studentService.deleteStudent(name);
    }


    @PostMapping("/updataeone")
    @Operation(summary = "更新学生名字")
    int updataStudent(String name, int id){
        return studentService.updateStudent(name,id);
    }
}

6. 最终结果显示     

 http://10.100.1.51:8081/doc.html

http://localhost:8081/doc.html

spring boot3 集成swagger3_第2张图片

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