Knife4j的基本使用

Knife4j的基本使用

一、引言

Knife4j 是一款基于 Spring Boot 的 API 文档生成工具,它继承了 Swagger 的优点并进行了扩展,提供了更美观的 UI 界面和更强大的功能。Knife4j 支持在线文档的生成、查看、调试以及离线文档的导出,极大地方便了前后端开发者的协作和 API 测试工作。

二、快速上手

1、引入依赖

首先,在你的 Spring Boot 项目的 pom.xml 文件中添加 Knife4j 的依赖。

<!-- 添加 Knife4j 依赖 -->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
    <version>4.1.0</version>
</dependency>

2、配置 Swagger

创建一个配置类 Knife4jConfig,用于配置 Swagger 的相关信息。

package cn.tedu.weibo.config;

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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.tedu.weibo.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("微博项目")
                .description("微博项目在线API文档")
                .version("1.0")
                .build();
    }
}

3、查看文档

启动你的 SpringBoot 应用,访问 http://localhost:8080/doc.html 地址即可查看生成的 Knife4j 接口文档。

三、常用注解

1、@Api

用于控制器类上,通过 tags 属性修改模块名称。

@Api(tags = "01.用户管理模块")
public class UserController {...}

2、@ApiOperation

用于方法上,配置方法的业务名称。

@ApiOperation(value = "注册功能")
public int reg(@RequestBody UserRegDTO userRegDTO){...}

3、@ApiModelProperty

用于 POJO 类的属性上,对请求参数或响应结果中的属性进行说明。

@ApiModelProperty(value = "用户名", required = true, example = "赵丽颖")
private String username;

四、总结

Knife4j 是一个强大的 API 文档生成工具,它简化了文档的生成和测试过程,提高了开发效率。通过上述步骤,你可以快速地在你的 Spring Boot 项目中集成 Knife4j,并生成美观且功能丰富的 API 文档。


版权声明:本博客内容为原创,转载请保留原文链接及作者信息。

参考文章

  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值