spring-boot - 配置服务器中的 Swagger 2 @ApiIgnore 属性切换
问题描述
我在 Sprinngboot 应用程序中使用 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 种微服务是外部的。
现在在使用 @ApiIgnore 隐藏微服务的 swagger doc 中,我们在 swagger 中忽略了 60 个,只显示了 10 个外部 api。
问题:
现在我要求外部用户只能在 swagger doc 中看到 10 个微服务,而内部微服务 swagger (70) 应该对开发人员和内部用户可见。
有什么方法可以在应用程序属性中为 prod 定义 @ApiIgnore 并仅显示 10 并且在开发配置属性中将隐藏 @ApiIgnore
解决方案
如果您使用配置文件,则不需要@ApiIgnore
注释。
定义开发人员资料。例如:
@Profile("dev")
@Controller
@RequestMapping("/internal/...")
@Api(value = "/internal/...", description = "Internal stuff")
public class OneOfTheInternalControllers { ... }
现在用配置文件标记所有内部控制器/端点。最后,如果您在生产模式下运行应用程序,则无需执行任何操作。API将@Profile("dev")
被隐藏。但是,如果您在本地或测试环境中运行应用程序,请传递以下 JVM 参数:
-Dspring.profiles.active=dev
如果您使用 IntelliJ,您可以在运行/调试配置中传递它:
最后,您应该以开发人员的身份看到您的所有 API。
推荐阅读
- c++ - OpenSSL C API:如何在程序 exec() 后恢复 TLS 连接?
- android - 将支持库迁移到 androidx 时出现问题
- java - 应用程序永远不会执行垃圾收集的任何情况?
- junit4 - 使用 Hamcrest (Java 8) 检查特定的地图值属性(谓词)
- java - 这可以使用java编程将pdf文件数据保存到数据库中吗?
- android - 架构组件和 Intent Extras
- javascript - openweathermap API 请求中的语法错误
- python - 在不同的文件夹中运行另一个 Python 脚本
- hyperledger - HyperLedger Sawtooth Seth 入门错误 2
- javascript - Gulp 构建任务在 docker 内部失败