SpringBoot集成Swagger&knife4j

前言

Swagger是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化RESTful风格的Web服务。目标是使客户端和文件系统作为服务器以同样的速度来更新文件的方法,参数和模型紧密集成到服务器。


一、引入Swagger的POM文件

 <!--生成 Swagger 文档的核心依赖-->
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>3.0.0</version>
</dependency>

 <!--提供 Swagger UI 界面的依赖-->
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>3.0.0</version>
</dependency>

二、添加Swagger配置类

代码如下(示例):

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;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    /**
     * groupName() 定义组名(根据自己需求定义名称)
     * apiInfo(apiInfo()) 指定文档标题和版本号
     * useDefaultResponseMessages()  启用默认响应消息
     * select()  选择要生成文档的接口
     * apis(RequestHandlerSelectors.basePackage()  指定要生成生成文档的接口的包路径
     * apis(RequestHandlerSelectors.withClassAnnotation()) 扫描被@RestController注解标记的类,生成文档
     * paths(PathSelectors.any())  包含在文档中的接口路径
     * build()  建 Docket 对象
     *
     * @return  Docket 对象
     */
    @Bean
    public Docket restApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("测试案例")
                .apiInfo(apiInfo("SpringBoot集成Swagger", "1.0.0"))
                .useDefaultResponseMessages(true)
                .forCodeGeneration(false) //是否生成代码 否
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.personal.demo.controller"))
//                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
                .paths(PathSelectors.any())
                .build();
    }
    /**
     * 使用 Springfox 生成 Swagger 文档时,用来设置 API 文档的基本信息的
     * 访问地址:http://ip:port/swagger-ui.html
     * @return
     */
    private ApiInfo apiInfo(String title, String version) {
        return new ApiInfoBuilder()
                .title(title)
                .description("更多请关注: https://swagger.io/")
                .version(version)
                .build();
    }
}


三、在WebMvc配置类中添加Swagger访问路径

 import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 解决swagger⽆法访问
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
        // 解决swagger的js⽂件⽆法访问
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

四、在yml文件中设置路径匹配策略

spring:
   mvc:
     pathmatch:
       matching-strategy: ant_path_matcher

五、在控制器类和方法添加注解

@Api(tags = "测试类页面")
@RestController
@RequestMapping("/test")
public class IndexController {

    @ApiOperation(value = "测试测试测试")
    @GetMapping("/index")
    public String Index(){
        return "Hello Swagger!";
    }
}

六、SpringBoot集成Swagger常见问题

(1)未在WebMvc配置类中添加Swagger访问路径会出现以下错误

SpringBoot集成Swagger&knife4j_第1张图片

(2)未在yml文件中指定路径匹配策略,会出现以下错误

SpringBoot集成Swagger&knife4j_第2张图片

Swagger2的访问地址格式:http://localhost:8080/swagger-ui.html#/
Swagger3的访问地址格式:http://localhost:8080/swagger-ui/index.html#/

七、Swagger增强版knife4j

(1)导入knife4j依赖

<dependency>
   <groupId>com.github.xiaoymin</groupId>
   <artifactId>knife4j-spring-boot-starter</artifactId>
   <version>2.0.8</version>
</dependency>

(2)添加配置文件

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiDescription;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.ArrayList;
import java.util.List;

/**
 * Swagger2配置信息
 */
@Configuration
@EnableSwagger2
@EnableKnife4j               //注意这个注解,开启knife4j重要注解
@EnableSwagger2WebMvc
public class Swagger2Config {

    @Bean(value = "defaultApi2")
    public Docket defaultApi2(){
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("测试1.0版本")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.personal.demo"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("若依权限API文档")
                .description("个人测试版本")
                .version("测试1.0版本")
                .build();
    }
}

(3)knife4j访问地址

http://localhost:8081/doc.html

(4)尚硅谷教程资料配置类

package com.atguigu.ssyx.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
import java.util.ArrayList;
import java.util.List;

/**
 * Swagger2配置信息
 */
@Configuration
@EnableSwagger2WebMvc
public class Swagger2Config {

    @Bean
    public Docket webApiConfig(){
        List<Parameter> pars = new ArrayList<>();
        ParameterBuilder tokenPar = new ParameterBuilder();
        tokenPar.name("userId")
                .description("用户token")
                //.defaultValue(JwtHelper.createToken(1L, "admin"))
                .defaultValue("1")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false)
                .build();
        pars.add(tokenPar.build());

        Docket webApi = new Docket(DocumentationType.SWAGGER_2)
                .groupName("webApi")
                .apiInfo(webApiInfo())
                .select()
                //只显示api路径下的页面
                .apis(RequestHandlerSelectors.basePackage("com.atguigu.ssyx"))
                .paths(PathSelectors.regex("/api/.*"))
                .build()
                .globalOperationParameters(pars);
        return webApi;
    }

    @Bean
    public Docket adminApiConfig(){
        List<Parameter> pars = new ArrayList<>();
        ParameterBuilder tokenPar = new ParameterBuilder();
        tokenPar.name("adminId")
                .description("用户token")
                .defaultValue("1")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false)
                .build();
        pars.add(tokenPar.build());

        Docket adminApi = new Docket(DocumentationType.SWAGGER_2)
                .groupName("adminApi")
                .apiInfo(adminApiInfo())
                .select()
                //只显示admin路径下的页面
                .apis(RequestHandlerSelectors.basePackage("com.atguigu.ssyx"))
                .paths(PathSelectors.regex("/admin/.*"))
                .build()
                .globalOperationParameters(pars);
        return adminApi;
    }

    private ApiInfo webApiInfo(){
        return new ApiInfoBuilder()
                .title("网站-API文档")
                .description("本文档描述了尚上优选网站微服务接口定义")
                .version("1.0")
                .contact(new Contact("atguigu", "http://atguigu.com", "atguigu"))
                .build();
    }

    private ApiInfo adminApiInfo(){
        return new ApiInfoBuilder()
                .title("后台管理系统-API文档")
                .description("本文档描述了尚上优选后台系统服务接口定义")
                .version("1.0")
                .contact(new Contact("atguigu", "http://atguigu.com", "atguigu"))
                .build();
    }
}

总结

本篇文章是记录学习SpringBoot集成Swagger入门过程,在集成Swagger时关注Swagger版本信息以及SpringBoot版本信息,不同版本的Swagger请求路径不一样。可能配置信息有所差别

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