springboot 集成 swagger2 与 knife4j

环境:
jdk: 1.8
springboot: 2.5.14 <2.6.0
swagger: 2.9.2

Springboot ✚ Swagger各版本整理

对于整合springboot 2.7 + swagger2 3.0.0 ,需要在配置文件中增加如下配置,否则会报异常!

spring:
 mvc:
   pathmatch:
     matching-strategy: ant_path_matcher

一、集成swagger2

引入swagger依赖:

       <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
            <version>2.9.2version>
        dependency>
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
            <version>2.9.2version>
        dependency>

编写SwaggerConfig

配置类上加@EnableSwagger2注解,也可以在启动类上加

package com.zhuang.mp.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Swagger的配置类
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //为当前包路径,控制器类包
                .apis(RequestHandlerSelectors.basePackage("com.zhuang.mp.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    //构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title("Spring Boot 集成 Swagger2 测试接口文档")
                //创建人
                .contact(new Contact("mrzhuang", "http://www.baidu.com", "[email protected]@qq.com"))
                //版本号
                .version("1.0")
                //描述
                .description("API 描述")
                .build();
    }
}

注意:记得修改配置类中basePackage的包路径,否则会swagger接口文档页面不显示接口。

controller层

使用@Api 和 @ApiOperation注解

package com.zhuang.mp.controller;

import com.zhuang.mp.entity.Teacher;
import com.zhuang.mp.service.ITeacherService;
import com.zhuang.mp.vo.ResponseVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * 

* 前端控制器 *

* * @author mrzhuang * @since 2022-12-21 */
@Api(tags = "教师接口") @RestController @RequestMapping("/mp/teacher") public class TeacherController { @Resource ITeacherService teacherService; @ApiOperation("获得全部的老师") @GetMapping("searchAll") public ResponseVo<List<Teacher>> searchAll(){ List<Teacher> teachers = teacherService.searchAll(); return new ResponseVo<>(teachers); } @ApiOperation("一对一多映射") @GetMapping("/selectByMap") public ResponseVo<List<Teacher>> selectByMap(){ List<Teacher> teachers = teacherService.selectByMap(); return new ResponseVo<>(teachers); } }

运行项目,访问swagger接口文档

访问:http://localhost:8080/swagger-ui.html
springboot 集成 swagger2 与 knife4j_第1张图片

注意:有可能访问不到网页

需要配置:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.
                addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
                .resourceChain(false);
    }

}

访问网页:http://localhost:9100/swagger-ui/index.html

二、集成 knife4j

引入依赖

      <dependency>
            <groupId>com.github.xiaoymingroupId>
            <artifactId>knife4j-openapi2-spring-boot-starterartifactId>
            <version>4.1.0version>
        dependency>

配置类

/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有,侵权必究!
 */

package io.renren.common.config;

import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;
import io.renren.common.constant.Constant;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

/**
 * Swagger配置
 *
 * @author Mark [email protected]
 */
@Configuration
@EnableSwagger2WebMvc
@AllArgsConstructor
public class SwaggerConfig{
    private final OpenApiExtensionResolver openApiExtensionResolver;

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            //加了ApiOperation注解的类,生成接口文档
            .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
            //包下的类,生成接口文档
            //.apis(RequestHandlerSelectors.basePackage("io.renren.modules.job.controller"))
            .paths(PathSelectors.any())
            .build()
            .extensions(openApiExtensionResolver.buildExtensions("Renren"))
            .directModelSubstitute(java.util.Date.class, String.class)
            .securitySchemes(security());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("人人开源")
            .description("renren-admin文档")
            .termsOfServiceUrl("https://www.renren.io")
            .version("5.x")
            .build();
    }

    private List<ApiKey> security() {
        return newArrayList(
            new ApiKey(Constant.TOKEN_HEADER, Constant.TOKEN_HEADER, "header")
        );
    }
}

访问接口文档

地址: http://localhost:8080/doc.html
springboot 集成 swagger2 与 knife4j_第2张图片

如果访问不到:
实现WebMvcConfigurer类增加资源访问的地址

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}

json 地址

地址: http://localhost:8080/v2/api-docs

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