SpringBoot/Swagger,仅显示 Swagger 上的特定控制器?

SpringBoot/Swagger, Show only specific Controllers on Swagger?

SwaggerConfig.java

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    public static final String AUTHORIZATION_HEADER = "Authorization";

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).securitySchemes(Arrays.asList(apiKey())).select()
                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)).paths(PathSelectors.any()).
                        build().apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("API").description("DEMO").version("v1").build();
    }

    private ApiKey apiKey() {
        return new ApiKey("JWT", AUTHORIZATION_HEADER, "header");
    }
}

此配置显示所有控制器,如何在 Swagger 上仅显示特定控制器?

1.同一包中的特定控制器

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).securitySchemes(Arrays.asList(apiKey())).select()
                .apis(RequestHandlerSelectors.basePackage("com.tm.x.y.z.your.controller")).paths(PathSelectors.any()).
                        build().apiInfo(apiInfo());
    }

显示包中的所有控制器 com.tm.x.y.z.your.controller


2。不同包中的特定控制器

  • 创建一个 class 注释(例如:ShowAPI 注释)

    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ShowAPI {
        String value() default "";
    }
    
  • 向控制器添加注解

     @RestController
     @ShowAPI
     public class ExampleController {
     }
    
  • 更改 swagger 配置

        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2).securitySchemes(Arrays.asList(apiKey())).select()
                    .apis(RequestHandlerSelectors.withClassAnnotation(ShowAPI.class)).paths(PathSelectors.any()).build()
                    .apiInfo(apiInfo());
        }

显示所有带有 class 注释的控制器是 ShowAPI