SpringBoot集成knif4j创建在线API文档

一直以来能够创建一个同项目一起发布的在线文档,曾经是很多程序员的梦想,偶然发现这个工具已经有了,测试之后发现还挺好用的,特地纪念。

这个工具就是knife4j,它是为Java MVC框架集成Swagger 生成Api文档的增强解决方案,其前身是swagger-bootstrap-ui。推荐采用了swagger的新增强版knife4j来生成API接口文档。knife4j的使用方法和swagger几完全一样。

1.引入pom.xml依赖:

 

<!--(老版本)引用依赖包-->
<dependency>
  <groupId>com.github.xiaoymin</groupId>
  <artifactId>swagger-bootstrap-ui</artifactId>
  <version>1.9.6</version>
</dependency>

<!--(新版本)swagger增强工具依赖包,方便生成接口文档。非必须导入-->
<dependency>
     <groupId>com.github.xiaoymin</groupId>
     <artifactId>knife4j-spring-boot-starter</artifactId>
     <version>2.0.1</version>
</dependency>

2.配置SwaggerConfig类:

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

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any()).build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("SpringBoot 测试项目")
                .description("This is a restful api document of")
                .description("SpringBoot整合Swagger,详细信息......")
                .version("1.0")
                .contact(new Contact("作者","blog.csdn.net","xxxxxxx@qq.com"))
                .license("Home")
                .licenseUrl("http://localhost:9090/swagger-ui.html")
                .build();
    }
}

可以看到,内容上和以前的swagger配置类一致的,唯一的变化是类注解需要比原来的swagger多加一个 @EnableSwaggerBootstrapUi。这样knife4j的所有配置都完成了。

以上有两个注解需要特别说明,如下:

@EnableSwagger2 
这个注解是Springfox-swagger框架提供的使用Swagger注解,该注解不可以省略

@EnableKnife4j
这个注解是knife4j提供的增强注解,Ui提供了例如动态参数、参数过滤、接口排序等增强功能,
如果你想使用这些增强功能就必须加该注解,否则可以不用加

3.在Controller上增加注解

@Api(tags = "统一异常处理测试接口")
@RestController
@RequestMapping(value="/api")
public class UserRestController {

    @ApiOperation(value = "新增用户",notes="新增用户,post 方式")
    @PostMapping("/user")
    public boolean insert(@RequestBody User user) {
        System.out.println("开始新增...");
        //如果姓名为空就手动抛出一个自定义的异常!
        if(null == user.getUsername()){
            throw  new BizException("-1","用户姓名不能为空!");
        }
        return true;
    }

    @ApiOperation(value = "查询用户列表",notes="查询用户列表 get 方式")
    @GetMapping("/users")
    public ResultBody findByUser(User user) {
        System.out.println("开始查询...");
        List<User> userList = new ArrayList<>();
        User user2 = null;

        for(int i=0; i<10; i++) {
            user2 = new User();
            user2.setId("user_"+i);
            user2.setUsername("username_"+i);
            user2.setNickname("laowu "+i);
            userList.add(user2);
        }
        return ResultBody.success(userList);
    }

上面就是一个普通的Controller,里面用到了2个注解:

@Api(tags = "统一异常处理测试接口"), 这个注解是类级别的注解,里面的参数tags里面其实是对当前类的功能做概况说明
@ApiOperation(value = "新增用户",notes="新增用户,post 方式")
这个ApiOperation注解是方法级的注解,是对当前的方法的功能做介绍说明,

其实swagger有很多注解,常用的是这些:

  • Api Api 用在类上,说明该类的作用
  • ApiModel 描述一个Model的信息
  • ApiModelProperty 描述一个model的属性。
  • ApiOperation 用在方法上,说明方法的作用
  • ApiParam 请求属性
  • ApiResponse 响应配置
  • ApiResponses 响应集配置
  • ResponseHeader 响应头设置

4.在SpringBoot启动类上增加注解
 

@SpringBootApplication
@EnableSwagger2
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

SpringBoot启动类上需要增加@EnableSwagger2这个注解。

配置了这么多,该看看运行起来的效果了,运行springboot项目,自动生成接口文档,

访问在线API文档地址: http://localhost:8080/doc.html

访问swagger的地址:   http://localhost:8080/swagger-ui.html

这样看起来是不是比普通的Sawgger看起来功能更完善了? 左侧的导航栏可以列出当前工程里面所有的控制器,以及所有添加了Swagger注解的类。

还可以做接口测试:

比如我打开了统一异常处理测试接口这个控制器,下面会列出新增用户何查询用户列表两个方法,还贴心的列出类这里handler的请求方式,然后在右侧会打开一个标签页,标题就是这个handler注解,

@ApiOperation(value = "查询用户列表",notes="查询用户列表 get 方式")
是ApiOperation注解里面value里面的内容

在这个大标签页里面会有两个小的标签页,分别是文档和测试,默认打开的是文档这个标签页,这个标签页里是当前handler方法的比较详细的描述,接口描述的内容就是ApiOperation注解里面notes参数的值,因此在实际情况下应该把这个参数的内容写的更完善一些,测试时看起来就比较完整了。

这里列出了
接口地址
请求方式
consumes 
produces 
接口描述 
请求参数
响应状态
响应参数
响应示例
这个几个最常用到的项目。

点击右边的调试标签,打开这个接口的调试窗口

这个是完整的调试窗口,这里列出了这个接口参数的具体数据,点击发送就可以向后台发送请求,返回结果也是默认用比较美观的方式展示出来,同时还给出了 响应内容、Raw、Headers、Curl 这几个功能

  • 响应内容:是后台返回的经过美化的jsong格式
  • Raw:里面是原始的json数据
  • Headers: 请求头
  • Curl:Curl命令的具体参数,这个在Linux下测试接口非常有用
     

更贴心的一个功能,这里还提示类这个接口的执行时间

这个功能对于优化接口的性能很帮助。

相信看到这里的小伙伴对knif4j已经有了比较直观的认识,赶紧来试试吧。

 

 

 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sure! To integrate Spring Boot with Knife4j, you can follow these steps: 1. Add the required dependencies to your project's `pom.xml` file: ```xml <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>2.0.2</version> </dependency> ``` 2. Create a new configuration class, typically named `SwaggerConfiguration`, and annotate it with `@Configuration`: ```java @Configuration public class SwaggerConfiguration { } ``` 3. Inside the `SwaggerConfiguration` class, add the necessary bean definitions for `Docket` and `ApiInfo`: ```java @Configuration public class SwaggerConfiguration { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) // Set your controller package .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Your API Documentation") .description("Description of your API") .version("1.0.0") .build(); } } ``` 4. Make sure to update the `basePackage` value in the `RequestHandlerSelectors` to match the package where your Spring MVC controllers are located. 5. Run your Spring Boot application, and you should be able to access the Knife4j swagger UI at `http://localhost:8080/doc.html`, where `8080` is your application's port. That's it! You have now integrated Knife4j with your Spring Boot application. You can customize the Swagger configuration further according to your requirements.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值