SpringBoot 集成 Swagger 3.0 和 knife4j 文档教程

SpringBoot 项目集成 Swagger 3.0 文档

  1. 添加依赖

    在 SpringBoot 项目中,在 pom 文件中添加 Swagger 3.0 的依赖

    
    <dependency>
      <groupId>io.springfoxgroupId>
      <artifactId>springfox-boot-starterartifactId>
      <version>3.0.0version>
    dependency>
    
  2. 创建 Swagger 配置类

    @Configuration
    @EnableOpenApi
    public class SwaggerConfig {
      @Bean
      public Docket createRestApi() {
        // 文档信息
        ApiInfo apiInfo = new ApiInfoBuilder().title("Swagger3 接口文档")
          .description("Swagger3 接口文档")
          .contact(new Contact("shijialeya", "http://www.shijialeya.top/", "[email protected]"))
          .version("1.0")
          .build();
    
        //返回文档摘要信息
        return new Docket(DocumentationType.OAS_30)
          // 文档信息
          .apiInfo(apiInfo)
          .select()
          .apis(RequestHandlerSelectors.withMethodAnnotation(Operation.class))
          .paths(PathSelectors.any())
          .build();
      }
    }
    
  3. 在 application.properties 文件中添加配置

    spring.mvc.pathmatch.matching-strategy=ant_path_matcher
    
  4. 创建 Controller 测试接口

    创建接口时使用 @Api 注解和 @Operation 注解。

    @RestController
    @RequestMapping("hello")
    @Api(tags = "hello 模块接口")
    public class HelloController {
      @GetMapping("test")
      @Operation(summary = "测试接口")
      @ApiImplicitParams({
        @ApiImplicitParam(name = "name", value = "用户名", dataTypeClass = String.class),
        @ApiImplicitParam(name = "age", value = "年龄", dataTypeClass = Integer.class)
      })
      public String test(String name, int age) {
        return name + ": " + age + ": " + LocalDateTime.now().toString();
      }
    }
    
  5. 访问查看

    启动 SpringBoot 启动类,浏览地址:http://localhost:端口号/swagger-ui/index.html

    如果做了访问权限限制,请将 /swagger-ui 下的地址放行,即可看到接口的信息。

    SpringBoot 集成 Swagger 3.0 和 knife4j 文档教程_第1张图片

SpringBoot 项目集成 knife4j 文档

在以上的基础下,在 pom 文件下添加以下依赖即可:


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

启动 SpringBoot 启动类,浏览地址:http://localhost:端口号/doc.html

SpringBoot 集成 Swagger 3.0 和 knife4j 文档教程_第2张图片

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