SpringBoot/Swagger, Show only specific Controllers on Swagger?

Viewed 2019
  • Spring boot: 2.1.3.RELEASE
  • Java 8
  • Springfox-swagger2: 2.9.2

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");
    }
}

This config show all Controllers, how to show only specific Controllers on Swagger?

1 Answers

1. Specific Controllers in same package

    @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());
    }

Show all Controllers in package com.tm.x.y.z.your.controller


2. Specific Controllers in different packages

  • Create an class annotation(ex: ShowAPI annotation)

    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ShowAPI {
        String value() default "";
    }
    
  • Add annotation to Controller

     @RestController
     @ShowAPI
     public class ExampleController {
     }
    
  • Change swagger config

        @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());
        }

Show all controller with class annotation is ShowAPI

Related