SpringBoot集成knife4j

https://doc.xiaominfo.com/

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

 

posted @   Bonnie_ξ  阅读(453)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示