首先引入依赖
SpringBoot3只支持OpenAPI3规范。
<!--knife4j-openapi3起步依赖-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.1.0</version>
</dependency>
静态资源映射
在WebMvcConfig配置类中设置静态资源映射。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
//处理静态资源无法访问
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/");
//处理swagger无法访问
registry.addResourceHandler("/swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/doc.html")
.addResourceLocations("classpath:/META-INF/resources/");
//处理swagger的js文件无法访问
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
SwaggerConfig配置类
设置OpenAPI的基础参数。
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("接口文档")
.contact(new Contact().name("翰戈.summer"))
.version("1.0")
.description("接口文档")
.license(new License().name("Apache 2.0")));
}
}
yml配置文件
其中分组配置可以有多个,扫描不同的controller包就行。
# springdoc-openapi配置
springdoc:
group-configs:
- group: 接口文档
packages-to-scan: com.demo.controller
# knife4j增强配置
knife4j:
enable: true
setting:
language: zh-CN
注解的使用
使用OpenAPI3的规范注解。
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Tag(name = "接口演示")
@RestController
@RequestMapping("/demo")
public class DemoController {
@Operation(summary = "demo")
@GetMapping
public String demo() {
return "success!";
}
}
效果展示
通过http://localhost:8080/doc.html来访问接口文档。