SpringBoot集成Knife4j2.0.2版Swagger(接口及字段排序、生产环境关闭)_小红帽的博客-CSDN博客_knife4j 排序

knife4j官网

https://doc.xiaominfo.com/knife4j/

一、添加pom依赖

<properties>
        <knife4j.version>2.0.2</knife4j.version>
        <springfox-swagger-ui.version>2.9.2</springfox-swagger-ui.version>
</properties>

<dependencies>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>${knife4j.version}</version>
        </dependency>
        <dependency>
            <!--兼容原版SwaggerUI-->
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${springfox-swagger-ui.version}</version>
        </dependency>
 </dependencies>  

二、书写Swagger配置

@Configuration
@EnableSwagger2
@EnableKnife4j
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfig {

    /**
     * API分组
     */
    @Bean(value = "apiV1")
    public Docket apiV1() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("v1")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.demo.controller.v1"))
                .paths(PathSelectors.any())
                .build();
    }

    @Bean(value = "apiV2")
    public Docket apiV2() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("v2")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.demo.controller.v2"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("项目 Restful API 说明文档")
                .contact("作者")
                .description("基于Swagger2和Knife4j实现的接口文档")
                .termsOfServiceUrl("http://localhost:8080/")
                .version("1.0")
                .build();
    }

}

三、配置Model按照顺序按定义排序

高版本的Knife4j配置请参考此文

@Component
public class CustomApiModelPropertyPositionBuilder implements ModelPropertyBuilderPlugin {

  private Log log = LogFactory.getLog(getClass());

  @Override
  public boolean supports(DocumentationType delimiter) {
    return SwaggerPluginSupport.pluginDoesApply(delimiter);
  }

  @Override
  public void apply(ModelPropertyContext context) {

    Optional<BeanPropertyDefinition> beanPropertyDefinitionOpt = context.getBeanPropertyDefinition();
    Optional<ApiModelProperty> annotation = Optional.absent();

    if (context.getAnnotatedElement().isPresent()) {
      annotation = annotation.or(findApiModePropertyAnnotation(context.getAnnotatedElement().get()));
    }

    if (context.getBeanPropertyDefinition().isPresent()) {
      annotation = annotation.or(findPropertyAnnotation(context.getBeanPropertyDefinition().get(), ApiModelProperty.class));
    }

    if (beanPropertyDefinitionOpt.isPresent()) {
      BeanPropertyDefinition beanPropertyDefinition = beanPropertyDefinitionOpt.get();
      if (annotation.isPresent() && annotation.get().position() != 0) {
        return;
      }

      AnnotatedField field = beanPropertyDefinition.getField();
      Class<?> clazz = field.getDeclaringClass();
      Field[] declaredFields = clazz.getDeclaredFields();
      Field declaredField;

      try {
        declaredField = clazz.getDeclaredField(field.getName());
      } catch (NoSuchFieldException | SecurityException e) {
        log.error("", e);
        return;
      }

      int indexOf = -1;
      for (int i = 0; i < declaredFields.length; i++) {
        if(declaredFields[i].equals(declaredField)) {
            indexOf = i;
            break;
        }
      }
      if (indexOf != -1) {
        context.getBuilder().position(indexOf);
      }

    }

  }

}

四、配置Controller接口排序

@Api(tags = "订单管理", position = 10)
@RestController
@RequestMapping("v1/order")
public class OrderController {

    @PostMapping
    @ApiOperation("创建订单")
    @ApiOperationSupport(order = 10)
    public void create() {


    }

    @DeleteMapping
    @ApiOperation("删除订单")
    @ApiOperationSupport(order = 20)
    public void delete() {

    }

    @GetMapping
    @ApiOperation("查看订单")
    @ApiOperationSupport(order = 30)
    public void get() {

    }

    @PutMapping
    @ApiOperation("修改订单")
    @ApiOperationSupport(order = 40)
    public void update() {

    }

}

说明:
• 该功能属于knife的增强功能,需要在浏览器上开启增强功能
• @Api(tags = “订单管理”, position = 10),作用在controller上,表示该接口排序值为10,越小越靠前。(建议以10倍间隔,方便插入新接口/方法)
• @ApiOperationSupport(order = 10),作用在方法上,也是越小排越前
开启增强功能

五、配置生产环境关闭Swagger

• 方法一:基于动态spring profile(推荐)

# yml配置
spring:
  profiles:
    active: prod
@Configuration
@EnableSwagger2
@EnableKnife4j
@Profile("!prod")
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfig {
    
    // ......上文的配置类
    
}

• 方法二:application.yml配置

knife4j:
  production: true #停用Swagger文档

原网址: 访问
创建于: 2022-02-21 20:55:51
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论