如何在 swagger-ui 中隐藏特定方法?

How can I hide a specific method in swagger-ui?

我目前在Spring Boot 2中使用swagger-ui 2.9.2版本,每个运行环境我想展示的方法都不一样,所以我想知道如何做. (环境示例:测试、开发、生产...)

比如我想在dev环境中展示A方法,但是我不想在prod环境中展示。

使用@Profile("dev"),swagger-ui本身的配置可以针对每个环境设置不同,但我想做的是展示swagger,但我想展示不同的具体方法每个环境..

提前感谢您的回答。

已添加:

@EnableSwagger2
@Configuration
public class SwaggerConfig {

    @Bean
    public Docket testApi() {
        String apiDomain = "test";
        String apiName = apiDomain + " API";

        ApiInfo apiInfo = new ApiInfoBuilder()
                .title(apiName)
                .description(apiName + " Document Prototype")
                .version("0.0.1")
                .build();

        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(apiDomain)
                .apiInfo(apiInfo)
                .select()
                .apis(getSelector(API_BASE_PACKAGE + "." + apiDomain))
                .paths(PathSelectors.any())
                .build();
    }

    private Predicate<RequestHandler> getSelector(String basePackage){

        // Profiles is a custom class util    
        return Profiles.isProd() ? Predicates.and(RequestHandlerSelectors.basePackage(basePackage), handler -> !handler.isAnnotatedWith(IgnoreForProd.class))
                : RequestHandlerSelectors.basePackage(basePackage);
    }
}

为此,您需要 spring @Profile 注释来为 Swagger UI 创建自定义 Docket 实例。

假设您想在生产环境中忽略特定的控制器方法。

首先,您需要创建自定义注释。没有它你也可以这样做,但这将是最干净的解决方案。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface IgnoreForProd {
}

然后注释掉你想在生产中忽略的控制器方法。

//..Spring and swagger annotations
@IgnoreForProd
public Pet postTestPetForSale(Pet pet) {
   //...controller code
}

最后,您需要为生产设置 docket 实例。

@Profile("prod")
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket postsApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("public-api")
                .apiInfo(apiInfo())
                .select()
                     // This is the part that will ignore the method
                    .apis((handler) -> !handler.isAnnotatedWith(IgnoreForProd.class))
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("API")
                .description("API reference for developers")
                .build();
    }

}