【发布时间】:2021-05-19 07:20:05
【问题描述】:
我有一个 Spring Boot REST API 应用程序,我集成了 Swagger 以获取文档,还使用它来测试带有 Swagger-UI 的 API。
现在我的任务是在我们的生产环境(公共域)上禁用 Swagger-UI,并在我们的私有 IP 上的开发环境中启用它。
【问题讨论】:
标签: java spring-boot swagger-ui springfox
我有一个 Spring Boot REST API 应用程序,我集成了 Swagger 以获取文档,还使用它来测试带有 Swagger-UI 的 API。
现在我的任务是在我们的生产环境(公共域)上禁用 Swagger-UI,并在我们的私有 IP 上的开发环境中启用它。
【问题讨论】:
标签: java spring-boot swagger-ui springfox
使用 Swagger vr-3.0.0,我们可以在相应的环境配置文件 application.properties 文件中添加 springfox.documentation.enabled=false/true。
Like for prod server application-prod.properties 文件
springfox.documentation.enabled=false
对于开发服务器 application-dev.properties 文件
springfox.documentation.enabled=true
并通过在 VM 参数中指定配置文件来运行应用程序
-Dspring.profiles.active=prod/dev
【讨论】:
为了实现它,我在 Swagger Config 类和 application.properties 文件中进行了以下提到的更改。
我的 pom.xml,我在其中添加了以下依赖项以集成 swagger。
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
在我的 application-dev.properties 文件中,我添加了一个带有布尔值 true 的键值对
use-swagger=true
在我的 application-prod.properties 文件中,我将值更改为 false
use-swagger=false
现在,终于在我的 SwaggerConfig 类中,我使用上面的键来启用/禁用我的 Swagger-UI
@Configuration
public class SwaggerConfig implements EnvironmentAware {
private Environment environment;
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.jkoder.example.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo())
.enable(Boolean.parseBoolean(environment.getProperty("use-swagger")));
}
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
}
enable(Boolean.parseBoolean(environment.getProperty("use-swagger"))) 此功能可让您在所需环境中启用或禁用 swagger-ui。
要执行 Spring Boot REST Api 应用程序,我们使用以下命令
在开发环境中-
nohup java -jar -Dspring.profiles.active=dev target/myapp-1.0.jar &
在生产环境中-
nohup java -jar -Dspring.profiles.active=prod target/myapp-1.0.jar &
【讨论】:
只需使用 @Profile 注释来注释您的配置
@Profile({"local", "dev"})
【讨论】: