knife4

发布时间 2023-05-28 22:18:56作者: kd最棒

使用knife4

  • knife4 集成了swagger

  • Swagger是一个生成,描述,调用Restful接口的Web服务,Swagger可以将项目中想要暴露的接口展现在页面上

image

image

  • 常常用于配合Yapi开发

image

  • knife4 导出保存于json文件中的swagger数据,再从导入到Yapi中

springboot中如何使用knife4

  • 导入pom依赖
<!--knife4 集成了swagger-->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>3.0.2</version>
</dependency>
  • 需要在项目中配置knife4
  1. 在WebMvcConfig配置文件上加入@EnableKnife4j, @EnableSwagger2注解
  2. 在WebMvcConfig配置文件中加入knife4配置类
  3. 设置knife4需要发送的请求的静态资源映射(其中doc.html是knife4自动生成的)
@EnableKnife4j
@EnableSwagger2
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    /**
     * 设置静态资源映射
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        //进行静态资源映射
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 配置swagger
     * @return
     */
    @Bean
    public Docket createRestApi() {
        //文档类型
        return new Docket(DocumentationType.SWAGGER_2)//docket类型
                .apiInfo(apiInfo())//api描述
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.nsjk.reggie.controller"))//api选择路径
                .paths(PathSelectors.any())
                .build();
    }

    //api描述
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("")
                .version("1.0")
                .description("接口文档")
                .build();
    }
}
  1. 需要在拦截器中将以下请求放行
"/doc.html",
"/webjars/**",
"/swagger-resources",
"/v2/api-docs"
  1. 在浏览器登录 http://localhost:8080/doc.html 即可进入操作页面

knife4中的常用注解

knife4注解是用于对页面显示的覆盖(相当于翻译),主要是为了便于理解接口文档页面

  • @Api:
    用在请求的类上,例如Controller,表示类的说明
  • @ApiModel:
    用在类上,通常是实体类,表示一个返回响应数据的信息
  • @ApiModelProperty:
    用在属性上,描述响应类的属性
  • @ApiOperation:
    用在请求的方法上,说明方法的用途,作用
  • @ApiImplicatParams:
    用在请求的方法上,表示一组参数说明
  • @ApiImplicatParam:
    用在@ApiImplicatParams注解中,指定一个请求参数的各个方面

image


可以看出前台页面的表现的改变

image