集成Knife4j的基本步骤
在Spring Boot项目中添加Knife4j依赖,需在pom.xml中引入以下依赖(以Maven为例):
<dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>3.0.3</version> </dependency>确保Spring Boot版本与Knife4j兼容(如Spring Boot 2.6.x以上)。
配置Swagger基础信息
创建Swagger配置类,定义API文档的基本信息:
@Configuration @EnableSwagger2 @EnableKnife4j public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API文档标题") .description("API文档描述") .version("1.0") .build(); } }配置Knife4j增强功能
Knife4j提供了增强功能,如离线文档导出、接口分组等。在application.yml中添加配置:
knife4j: enable: true setting: language: zh-CN enableSwaggerModels: true enableDocumentManage: true访问Knife4j文档界面
启动项目后,通过以下URL访问文档界面:
- 默认Swagger UI:
http://localhost:8080/swagger-ui.html - Knife4j增强UI:
http://localhost:8080/doc.html
接口注解的使用
在Controller中使用Swagger注解描述接口:
@RestController @RequestMapping("/api") @Api(tags = "示例模块") public class DemoController { @GetMapping("/demo") @ApiOperation(value = "示例接口", notes = "详细描述") public String demo(@ApiParam("参数描述") String param) { return "success"; } }常见问题解决
若出现无法访问文档的问题,检查以下内容:
- 确认依赖版本无冲突
- 检查
@EnableSwagger2和@EnableKnife4j注解是否添加 - 确保Controller包路径在
basePackage中正确配置
安全配置(可选)
如需保护文档接口,可在Spring Security中配置放行路径:
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/doc.html", "/webjars/**", "/v2/api-docs").permitAll() .anyRequest().authenticated(); }