繁体   English   中英

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

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

我目前在Spring Boot 2中使用的是2.9.2版本的swagger-ui,每个运行环境我想展示的方法都不一样,不知怎么做。 (环境前:测试、开发、产品...)

例如,我想在 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实例。

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

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

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

然后对生产中要忽略的controller的方法进行注释。

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

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

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM