SpringBoot/Swagger,如何在Swagger中只显示特定的控制器?

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

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

2个回答

6

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. 不同包中的特定控制器

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

显示所有具有类注释 ShowAPI 的控制器

0

只需使用@ApiIgnore注解。

1- 忽略控制器类

@ApiIgnore 
@RestController
public class HelloController {
.....
.....
}

2- 忽略特定方法

@RestController
public class HelloController {
    
    @ApiIgnore 
    @RequestMapping(method = RequestMethod.GET, value = "/api/testmethod")
    public String sayHello() {
        return "Swagger Hello World";
    }
}

不对,你们项目中的某个架构师一定是采用了和@tienph(最高评分答案)建议的相同解决方案,并将注释命名为APIIgnore。 - Manish

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接