【问题标题】:Swagger 2 @ApiIgnore properties toggle in config server配置服务器中的 Swagger 2 @ApiIgnore 属性切换
【发布时间】:2026-01-26 17:30:01
【问题描述】:

我在 Spring Boot 应用中使用 swagger 2 (2.9.2)。

依赖:

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>



<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

代码:

package com.khan.vaquar.swagger;

import static com.google.common.base.Predicates.or;
import static springfox.documentation.builders.PathSelectors.regex;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.google.common.base.Predicate;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket postsApi() {
        return new Docket(DocumentationType.SWAGGER_2).groupName("vaquar khan public-api").apiInfo(apiInfo()).select().apis( RequestHandlerSelectors.basePackage( "com.khan.vaquar" ) )
                .paths(paths()).build();



    }
    private Predicate<String> paths() {
        return or(regex("/.*"), regex("/.*"));
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("vaquar khan public-api")
                .description("vaquar khan public-api app API reference for developers")
                .termsOfServiceUrl("XXX-YYY-ZZZ.com").contact("info@vkhan.com")
                .license("vaquar khan License").licenseUrl("Licence@vkhan.com").version("1.0").build();
    }

}

我有近 70 种不同的微服务,很多是内部的,只有少数 10 种微服务是外部的。

现在在 swagger doc 中使用 @ApiIgnore 隐藏微服务,我们在 swagger 中忽略了 60 个,只显示了 10 个外部 api。

问题:

现在我要求外部用户在 swagger doc 中只能看到 10 个微服务,而内部微服务 swagger (70) 应该对开发人员和内部用户可见。

有什么方法可以在应用程序属性中为 prod 定义 @ApiIgnore 并仅显示 10,而在开发配置属性中将隐藏 @ApiIgnore

【问题讨论】:

  • 你可以尝试使用@Profile("dev"),针对不同的环境使用不同的配置。
  • 如何在配置文件属性中使用注解,这是我的问题@apiIgnore 是注解

标签: spring-boot swagger-2.0 springfox


【解决方案1】:

如果您使用配置文件,则不需要 @ApiIgnore 注释。

定义开发者资料。例如:

@Profile("dev")
@Controller
@RequestMapping("/internal/...")
@Api(value = "/internal/...", description = "Internal stuff")
public class OneOfTheInternalControllers { ... }

现在用配置文件标记您的所有内部控制器/端点。最后,如果您在生产模式下运行应用程序,则无需执行任何操作。 @Profile("dev") API 将被隐藏。但是,如果您在本地或测试环境中运行应用程序,请传递以下 JVM 参数:

-Dspring.profiles.active=dev

如果你使用 IntelliJ,你可以在运行/调试配置中传递它:

最后,作为开发人员,您应该会看到所有的 API。

【讨论】: