springboot3.4.5 配置Knife4j 官方推荐使用
网址:
http://localhost:8080/doc.html#/home
一、注入依赖
<!-- SpringDoc OpenAPI UI --> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.7.0</version> </dependency>
<dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId> <version>4.5.0</version> </dependency>
二、配置类
package com.wt.config; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import org.springdoc.core.models.GroupedOpenApi; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class Knife4jConfig { // 配置文档信息 @Bean public OpenAPI openAPI(){ return new OpenAPI().info(new Info() .title("文档标题") .version("1.0") .description("文档描述") ); } // 配置功能分组,路由可以有多个 @Bean public GroupedOpenApi typeAPI(){ return GroupedOpenApi.builder().group("类型分组") .pathsToMatch("/type/**", "/test/**") .build(); } }
三、用法
1、实体类(描述返回值信息)
a、语法
@Schema(description = "返回值类型描述") 添加到 类或属性的注解
b、案例
package com.wt.pojo; import com.baomidou.mybatisplus.annotation.*; import java.io.Serializable; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; /** * @TableName news_type */ @TableName(value ="news_type") @Data @Schema(description = "类型实体类") public class Type implements Serializable { @TableId @Schema(description = "类型id") private Integer tid; @Schema(description = "类型name") private String tname; @Schema(description = "类型乐观锁") @Version private Integer version; @Schema(description = "类型逻辑删除") @TableLogic private Integer isDeleted; private static final long serialVersionUID = 1L; }
2、控制层
a、语法
@Tag(name = "分组(功能)描述")
@Operation(summary = "url描述")
@Parameter(description = "参数描述")
b、案例
package com.wt.controller; import com.wt.pojo.Type; import com.wt.service.TypeService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("type") // 分组描述,与swagger类似 @Tag(name = "类型管理") public class TypeController { @Autowired private TypeService typeService; // url 路由 描述 @Operation(summary = "获取数据") @GetMapping("get") // @Parameter 参数描述 public Type get(@Parameter(description = "类型id") @RequestParam(name = "id", required = false) Integer id){ Type type = typeService.getById(id); return type; } }
四、配置 展开参数的设置 yaml
springdoc:
default-flat-param-object: true # 平展参数
展开前
展开后