Spring Boot3整合knife4j(swagger3)
在Spring Boot 3中整合Knife4j(Swagger 3的升级版),首先需要引入Knife4j的依赖,然后配置Swagger 3。以下是一个简单的示例:
- 在
pom.xml
中添加Knife4j的依赖:
<dependencies>
<!-- 添加Knife4j依赖 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
</dependencies>
- 在
application.properties
或application.yml
中配置Knife4j:
# 配置Knife4j的基本路径,默认可以不配置
knife4j:
basic:
enable: true
# 基本路径
path: /doc
- 在Spring Boot启动类上添加
@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);
}
}
- 创建一个Swagger配置类,配置Swagger的基本信息:
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
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;
@Configuration
@EnableKnife4j
public class SwaggerConfig {
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
Docket docket=new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
return docket;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Knife4j 示例")
.description("这是一个使用Knife4j的Swagger3接口文档")
.contact(new Contact("开发者名字", "http://example.com", "example@example.com"))
.version("1.0")
.build();
}
}
- 创建一个Controller类,添加Swagger注解:
impor
评论已关闭