SpringBoot集成knife4j
1.添加pom文件
<!--knife4j 依赖 3.0.2版本会报错,springboot 2.3.4.RELEASE-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<!--swagger 依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
Knife4j里面集成了swagger的jar包,所以项目中有一个knife4j的jar包就能使用
2.添加配置文件
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; 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.ApiSelectorBuilder; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @Author nitric oxide * @Description * @Date 6:13 下午 2021/11/11 */ @EnableSwagger2 @Configuration public class SwaggerConfig { @Bean(value = "defaultApi2") public Docket defaultApi2() { ApiSelectorBuilder builder = new Docket(DocumentationType.SWAGGER_2) .enableUrlTemplating(false) .apiInfo(apiInfo()) // 选择那些路径和api会生成document .select() // 对所有api进行监控 .apis(RequestHandlerSelectors.any()) //这里可以自定义过滤
//.paths(PathSelectors.any()) .paths(this::filterPath); return builder.build(); } private boolean filterPath(String path) { boolean ret = path.endsWith("/error"); if (ret) { return false; } //这块可以写其他的过滤逻辑 return true; } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("title") .description("description") .termsOfServiceUrl("https://www.baidu.com") .version("1.0") .contact(new Contact("nitric oxide", "www.baidu.com", "123@qq.com")) .build(); } }
3.使用swagger注解标记接口
最后写一些swagger注解(不过我觉得上面的三个例子已经覆盖了大多数场景了)
swagger
http://192.168.30.1:8098/swagger-ui/index.html
knife4j 页面
http://192.168.30.1:8098/doc.html
故乡明
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!