SpringBoot 整合 knfe4j ,使用 OpenAPI3 规范
SpringBoot整合knife4j使用OpenAPI3规范的步骤如下:
- 在
pom.xml
中添加依赖:
<dependencies>
<!-- 添加knife4j的依赖 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<!-- 如果你使用的是Spring Boot 2.6及以上版本,请使用下面的依赖 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter-3</artifactId>
<version>3.0.3</version>
</dependency>
</dependencies>
- 配置
application.properties
或application.yml
,设置knife4j的相关配置:
# 设置knife4j的相关配置
knife4j:
enable: true
# 设置OpenAPI的相关配置
openapi:
scan-base-package: com.example.demo.controller # 扫描的包路径
group: default # 分组名称
contact:
name: John Doe
email: john.doe@example.com
url: http://johndoe.com
version: 1.0.0
title: Example API
description: This is a sample server Petstore server.
termsOfServiceUrl: http://swagger.io/terms/
license:
name: Apache 2.0
url: http://springdoc.org
externalDocs:
description: Find more info here
url: https://swagger.io
- 在SpringBoot启动类上添加
@EnableKnife4j
注解启用knife4j:
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableKnife4j // 启用Knife4j
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
- 创建Controller并使用
@Api
、@ApiOperation
等注解描述接口:
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@Tag(name = "Example", description = "Example API")
@RestController
public class ExampleController {
@Operation(summary
评论已关闭