Bootstrap

springboot 2.4.0 knife4j 3.0.1接口文档框架

本文介绍了springboot 2.4.0框架集成knife4j 3.0.1接口文档框架的流程。

原springboot启动类

public static void main(String[] args) {
        ConfigurableApplicationContext application= SpringApplication.run(Kinfe4jApplication.class, args);
        Environment env = application.getEnvironment();
        String host= null;
        try {
            host = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            logger.error("获取当前服务器HOST失败:{}",e);
            e.printStackTrace();
        }
        String springApplicationName=env.getProperty("spring.application.name");
        String port=env.getProperty("server.port");
        String contextPath=env.getProperty("server.servlet.context-path");
        String portAndContextPath = null;
        String applicationName = "未获取服务名称";
        if (null != applicationName){
            applicationName = springApplicationName;
        }

        if (null == contextPath){
            portAndContextPath = port;
        }else {
            portAndContextPath = port+contextPath;
        }
        logger.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\t"+
                        "----------------------------------------------------------",
                applicationName,
                portAndContextPath,
                host,portAndContextPath,
                host,portAndContextPath);
    }

Knife4j 配置类

springboot启动类上增加注解

@Configuration
@EnableSwagger2
@EnableKnife4j
@Import(BeanValidatorPluginsConfiguration.class)

knife4j配置类中扫描所有api


/**
     * https://gitee.com/xiaoym/swagger-bootstrap-ui-demo/blob/master/swagger-bootstrap-ui-demo/src/main/java/com/swagger/bootstrap/ui/demo/config/SwaggerConfiguration.java
     * 默认访问工程下所有api
     * 注意:web包下子包的类的类名,注解@RequestMapping("/v1")的映射地址,均不能相同
     * @return
     */
    @Bean(value = "defaultApi")
    public Docket defaultApi() {
        //分组/版本,名称
        String groupName="1.0.0版本";
        String author = "Huang Min";
        String homePage = "https://www.yuque.com/huangmins/java/hcds4q";
        String email = "huangmin@exc-led.com";
        String title = "多媒体文件处理服务的接口";
        String description = "多媒体文件处理服务 RESTful APIs";
        String termsOfServiceUrl = "https://www.yuque.com/huangmins/java/hcds4q";
        String version = "1.0.0";

        Contact contact = new Contact(author, homePage, email);

        ApiInfo apiInfo = new ApiInfoBuilder()
                .title(title)
                .description(description)
                .termsOfServiceUrl(termsOfServiceUrl)
                .contact(contact)
                .version(version)
                .build();

        Docket docket=new Docket(DocumentationType.SWAGGER_2)
                // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
                .apiInfo(apiInfo)
                .groupName(groupName)
                // 设置哪些接口暴露给Swagger展示
                .select()
                // 扫描所有有注解的api,用这种方式更灵活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 扫描所有 .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

knife4j配置类扫描指定包api

 /**
     * 上海50所的接口测试1
     *
     * @return
     */
    @Bean(value = "packageApiV2")
    public Docket packageApiV2() {
        //分组/版本,名称
        String groupName = "V2版本";
        String author = "Huang Min";
        String homePage = "https://doc.xiaominfo.com/guide/";
        String email = "huangmin@exc-led.com";
        String title = "多媒体文件处理服务的接口";
        String description = "多媒体文件处理服务 RESTful APIs";
        String termsOfServiceUrl = "https://www.yuque.com/huangmins/java/hcds4q";
        String version = "1.2.0";
        String basePackage = "com.exc.kinfe4j.web.v2";

        Knife4jDTO knife4jDTO = new Knife4jDTO(groupName, author, homePage, email, title, description, termsOfServiceUrl, version, basePackage);

        Docket docket = createDocket(knife4jDTO);
        return docket;
    }

    /**
     * 上海50所的接口测试2
     *
     * @return
     */
    @Bean(value = "packageApiV3")
    public Docket packageApiV3() {
        //分组/版本,名称
        String groupName = "50所V3";
        String author = "Huang Min";
        String homePage = "https://doc.xiaominfo.com/guide/";
        String email = "huangmin@exc-led.com";
        String title = "多媒体文件处理服务的接口";
        String description = "多媒体文件处理服务 RESTful APIs";
        String termsOfServiceUrl = "https://www.yuque.com/huangmins/java/hcds4q";
        String version = "1.3.0";
        String basePackage = "com.exc.kinfe4j.web.v3";

        Knife4jDTO knife4jDTO = new Knife4jDTO(groupName, author, homePage, email, title, description, termsOfServiceUrl, version, basePackage);

        Docket docket = createDocket(knife4jDTO);
        return docket;
    }


    /**
     * 创建 Docket
     *
     * @param knife4jDTO
     * @return Docket
     */
    private Docket createDocket(Knife4jDTO knife4jDTO) {
        String groupName = knife4jDTO.getGroupName();
        String author = knife4jDTO.getAuthor();
        String homePage = knife4jDTO.getHomePage();
        String email = knife4jDTO.getEmail();
        String title = knife4jDTO.getTitle();
        String description = knife4jDTO.getDescription();
        String termsOfServiceUrl = knife4jDTO.getTermsOfServiceUrl();
        String version = knife4jDTO.getVersion();
        String basePackage = knife4jDTO.getBasePackage();

        Contact contact = new Contact(author, homePage, email);

        ApiInfo apiInfo = new ApiInfoBuilder()
                .title(title)
                .description(description)
                .termsOfServiceUrl(termsOfServiceUrl)
                .contact(contact)
                .license("exc-led")
                .licenseUrl("https://www.exc-led.com/")
                .version(version)
                .build();

        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
                .apiInfo(apiInfo)
                .groupName(groupName)
                // 设置哪些接口暴露给Swagger展示
                .select()
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                // 扫描所有 .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

实体类的注解

#实体类的注解,声明被knife4j管理
@ApiModel
#字段的注解,example:默认参数
@ApiModelProperty(value = "返回码", example="200",notes = "返回200,400")

Controller 接口的注解参数

#接口类的注解
@Api
#接口的注解
@ApiOperation
#参数列表的注解
@ApiImplicitParams
#每一个参数的注解
@ApiImplicitParam

Controller 接口的排序

#类的排序,注解ApiSort,参数int类型参数,未添加该注解的排序在后
@ApiSort(3)
#接口的排序,注解@ApiOperationSupport(order=3),order参数int类型,未添加该注解的排序在后
@ApiOperationSupport(order=2)

配置文件

spring:
  application:
    name: Knife4j-3.x

#接口文档系统配置
knife4j:
  # true:启用knife4j增强模式, false:不启用knife4j增强模式
  enable: true
  #是否开启生产环境保护策略,生产环境下禁止访问接口文档系统,生产环境设置为true,开发环境设置为false,
  production: false
  #对Knife4j提供的资源提供BasicHttp校验,保护文档;production配置为true时,basic认证功能不可用
  basic:
    #开启BasicHttp功能
    enable: false
    username: admin
    password: 123321
  #是否开启一个默认的跨域配置,该功能配合自定义Host使用,cors: true
  #  cors: true
  #增强模式配置 https://doc.xiaominfo.com/knife4j/enhance.html

pom.xml配置

    
        27.0.1-jre
        3.0.1
        1.5.22
        1.8
    
    

    
        
            com.github.xiaoymin
            knife4j-spring-boot-starter
            ${knife4j.version}
            
                
                
                    guava
                    com.google.guava
                
                
                
                    swagger-annotations
                    io.swagger
                
            
        
        
        
            io.swagger
            swagger-annotations
            ${knife4j.annotations.version}
        
        
        
            com.google.guava
            guava
            ${guava.version}
        
    

GitHub工程示例

下载链接

启动工程

下载工程后, 导入idea, 启动成功, 如下图所示:

knife4j系统

进入系统页面

切换接口分组

下载查看离线接口文档

下载指定分组的离线接口文档

下载typora工具

官网下载地址:

查看离线接口文档