简介
在日常开发中,写接口文档是我们必不可少的,而Knife4j就是一个接口文档工具,可以看作是Swagger的升级版,但是界面比Swagger更好看,功能更丰富
使用
我使用的是springboot3.2.3 +knife4j 4.3.0,knife4j 4.4版本有问题。
引入依赖
<dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId><version>4.3.0</version></dependency>
注意springboot3只支持openaipi3!
配置
在application.yml中加入相关配置
# springdoc-openapi项目配置
springdoc:swagger-ui:path: /swagger-ui.htmltags-sorter: alphaoperations-sorter: alphaapi-docs:path: /v3/api-docsgroup-configs:- group: 'default'paths-to-match: '/**'packages-to-scan: com.example.swagger3.controller #包扫描路径
# knife4j的增强配置,不需要增强可以不配
knife4j:enable: truesetting:language: zh_cn
或者也可以用配置类来配置信息:
@Configuration
public class Knife4jConfig {@Beanpublic GroupedOpenApi adminApi(){return GroupedOpenApi.builder().group("admin-api") //分组名称.pathsToMatch("/admin/**") //文档包含的API路径.build();}@Beanpublic OpenAPI customOpenAPI(){return new OpenAPI().info(new Info().title("API接口文档").version("1.0").description("API接口文档").contact(new Contact().name("yi")));}
}
运行springboot主程序,访问http://localhost:8080/doc.html如出现界面即配置成功。
常用注解
使用实例:
controller
@RestController
@Tag(name = "用户接口", description = "hello控制器")
public class HelloController {@GetMapping("/hello")@Operation(summary = "hello接口")public Result<People> hello(){
// return "OK";return new Result<People>(new People("yi",18),200);}@GetMapping("/hello_withparam")@Operation(description = "带参数的hello接口")public Result<People> hello_param(@Parameter(description = "名字") String name){return null;}
}
dto
@Data
@AllArgsConstructor
@Schema( description= "人类")
public class People {@Schema(title = "标题a",description = "名字")String name;@Schema(description = "年龄")Integer age;
}