【SpringBoot】Swagger&Knif4j接口文档集成

[TOC]

序:接口文档

​ 在开发过程中,接口文档是非常重要的一环,在 Spring Boot 中,我们可以通过集成第三方来实现接口文档的自动生成。

​ 通过注解来描述接口,然后根据这些注解自动生成接口文档,它不仅方便开发者查看和理解接口的功能和参数,还能帮助前后端开发协同工作,提高开发效率。

​ 常用的接口文档,有Swagger和Knife4j,推荐Knife4j 。

  • 作用
    • 方便前后端开发对接
    • 方便沉淀和维护
    • 支持在线调试、在线测试
    • 可以导出接口文档

1 Swagger

Swagger 是一个 RESTful 接口文档的规范和工具集,它的目标是统一 RESTful 接口文档的格式和规范。

1.1 基本信息

1.2 接入步骤

  • 根据maven中央仓库,引入包

    根据SpringBoot选择对应的版本,我的是SpringBoot版本是2.7.15

    • Swagger后端包

      <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
      <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
      </dependency>
    • Swagger前端包

      <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
      <dependency>
          <groupId>io.springfox</groupId>
          <artifactId>springfox-swagger-ui</artifactId>
          <version>2.9.2</version>
      </dependency>
  • 创建配置类

    新建SwaggerConfig.java 文件

    package com.leovany.usercenter.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;
    
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
    
        @Bean
        public Docket productApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    // 这里一定要标注你控制器的位置
                    .apis(RequestHandlerSelectors.basePackage("com.leovany.usercenter.controller"))
                    .paths(PathSelectors.any())
                    .build();
        }
    
        /**
         * api 信息
         *
         * @return
         */
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("用户中心")
                    .description("用户中心接口文档")
                    .termsOfServiceUrl("https://github.com/leovany")
                    .contact(new Contact("leovany", "https://github.com/leovany", "xxx@qq.com"))
                    .version("v1.0.0")
                    .build();
        }
    
    }
    
  • 配置路径匹配策略

    • 如果 springboot version >= 2.6,需要添加如下配置

      spring:
          mvc:
              pathmatch:
              matching-strategy: ANT_PATH_MATCHER
    • 原因

      Spring MVC 的路径匹配策略是 ant-path-matcher,而 Spring Boot 2.6.x版本的默认匹配策略是 path-pattern-matcher,这就导致启动时报错,错误内容信息:

      Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
      ...
  • 启动项目,输入地址

    地址:http://localhost:8080/swagger-ui.html

    image-20231213233747762

2 Knife4j

knife4j是为Java MVC框架集成Swagger生成Api文档的增强解决方案

2.1 基本信息

2.2 接入步骤

  • 根据maven中央仓库,引入包

    根据SpringBoot选择对应的版本,我的是SpringBoot版本是2.7.15

    <!--  https://mvnrepository.com/artifact/com.github.xiaoymin/knife4j-spring-boot-starter -->
    <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>knife4j-spring-boot-starter</artifactId>
        <version>3.0.3</version>
    </dependency>
  • 创建配置类

    新建Knife4jConfig.java 文件

    package com.leovany.usercenter.config;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Profile;
    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.EnableSwagger2WebMvc;
    
    /**
     * 自定义 Knife4j 接口文档的配置
     */
    @Configuration
    @EnableSwagger2
    public class Knife4jConfig {
    
        @Bean(value = "defaultApi2")
        public Docket defaultApi2() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    // 项目controller的位置
                    .apis(RequestHandlerSelectors.basePackage("com.leovany.usercenter.controller"))
                    .paths(PathSelectors.any())
                    .build();
        }
    
        /**
         * api 信息
         *
         * @return
         */
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("用户中心")
                    .description("用户中心接口文档")
                    .termsOfServiceUrl("https://github.com/leovany")
                    .contact(new Contact("leovany", "https://github.com/leovany", "xxx@qq.com"))
                    .version("1.0.0")
                    .build();
        }
    }
    
  • 配置路径匹配策略

    • 如果 springboot version >= 2.6,需要添加如下配置

      spring:
          mvc:
              pathmatch:
              matching-strategy: ANT_PATH_MATCHER
    • 原因

      Spring MVC 的路径匹配策略是 ant-path-matcher,而 Spring Boot 2.6.x版本的默认匹配策略是 path-pattern-matcher,这就导致启动时报错,错误内容信息:

      Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
      ...
  • 配置是否屏蔽文档接口

    在文件application.yml配置,生产环境注意防止暴露接口文档(production设置为true)

    knife4j:
      # 开启增强配置
      enable: true
      # 是否屏蔽接口文件(true=屏蔽,false=不屏蔽)
      production: false
  • 启动项目,输入地址

    地址:http://localhost:8080/doc.html

    image-20231213235156936

  • 19
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一种便捷的框架,它可以快速地搭建Java应用程序,并且它对于集成其他组件和框架也十分方便。而Knife4j则是一种集成度很高的API文档工具,它可以将接口文档Swagger的基础上大幅度优化。在Spring Boot中使用Knife4j整合API文档也非常简单。 首先,我们需要在Spring Boot的项目中引入Knife4j依赖,可以在pom.xml文件中加入以下代码: ``` <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>2.2.7</version> </dependency> ``` 这样Knife4j就会被自动集成到Spring Boot的应用中。 接下来,我们需要在Controller方法上增加注解,并且配置一些信息才能生成接口文档。 ``` @GetMapping("/hello") @ApiOperation(value = "示例API接口", notes = "这是一个示例API接口") @ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "用户名", required = true, dataType = "String", paramType = "header") }) public String hello(@RequestHeader String name){ return "Hello, " + name + "!"; } ``` 其中@GetMapping是Spring Boot的注解,用于标记这是一个GET请求。@ApiOperation和@ApiImplicitParams则是Knife4j的注解,它们分别用于注释方法和方法参数的信息。 最后,在启动Spring Boot应用后,访问http://localhost:8080/doc.html 就可以看到生成的接口文档了。这个文档列表会列出所有接口的URL、HTTP方法、请求参数、响应结果等信息,非常直观和有用。通过Knife4j可以使API文档生成更加高效、直观,方便开发者理解和调用接口。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值