【发布时间】:2021-05-17 04:28:13
【问题描述】:
我已经大摇大摆地插入了我的 Spring Boot 应用程序。 Spring boot 允许您拥有每个环境的属性文件。有没有办法在生产环境中禁用 swagger?
【问题讨论】:
标签: java spring spring-boot swagger swagger-ui
我已经大摇大摆地插入了我的 Spring Boot 应用程序。 Spring boot 允许您拥有每个环境的属性文件。有没有办法在生产环境中禁用 swagger?
【问题讨论】:
标签: java spring spring-boot swagger swagger-ui
将你的 swagger 配置放入单独的配置类中,并使用 @Profile 注释对其进行注释 -> 以便仅在某些配置文件中将其扫描到 Spring 上下文中。
例子:
@Configuration
@EnableSwagger2
@Profile("dev")
public class SwaggerConfig {
// your swagger configuration
}
您可以通过命令行:--spring.profiles.active=dev 或通过配置文件:spring.profiles.active=dev 来定义您的 Spring Boot 应用程序正在运行的配置文件。
Read this section of Spring Boot docs for more info about @Profile
【讨论】:
如果您在多个环境中工作,那么您也可以使用 @Profile 作为数组
@Configuration
@EnableSwagger2
@Profile({"dev","qa"})
public class SwaggerConfig {
// your swagger configuration
}
【讨论】:
使用 swagger 3.0.0 版本,您可以在相应的环境配置文件application.properties 文件中添加springfox.documentation.enabled=false。例如,我已将此添加到 application-prod.properties 以在生产中禁用(在运行应用程序时,您必须使用 VM args 指定配置文件,例如 -Dspring.profiles.active=prod)
【讨论】:
这是我的配置类:
@Configuration
@Profile("swagger")
@EnableSwagger2
public class SwaggerConfig {
@Value("${info.build.version}")
private String buildVersion;
@Bean
public Docket documentation() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(regex("/rest/.*"))
.build()
.pathMapping("/")
.apiInfo(metadata());
}
private ApiInfo metadata() {
return new ApiInfoBuilder()
.title("API documentation of our App")
.description("Use this documentation as a reference how to interact with app's API")
.version(buildVersion)
.contact(new Contact("Dev-Team", "https://dev-website", "dev@mailbox"))
.build();
}
}
无论哪里需要 Swagger,我都会将配置文件 swagger 添加到环境变量 SPRING_PROFILES_ACTIVE
【讨论】:
除了使用配置文件配置 Spring 的答案之外,考虑在反向 HTTP 代理上设置规则以阻止从 LAN 外部访问 Swagger 端点。这将为您提供一些针对 Swagger 端点攻击的深度防御。
【讨论】:
对于那些使用代码生成(生成 Swagger2SpringBoot)的人:
完成。
【讨论】:
有环境配置
@配置
@EnableSwagger2
@Profile("devone")
应用程序.yaml
profiles:
active:
${MY_ENV:devone}
MY_ENV 您将从文件中读取,例如 .env
.env 文件内容: MY_ENV=产品
在生产中保留其他 .env 文件仅用于生产凭据。
【讨论】:
spring.profiles.active=production with @Profile("!production") 帮助我关闭了产品中的招摇。
例如:-
@Profile("!production")
@Component
@EnableSwagger2
public class SwaggerConfig {
//TODO
}
【讨论】: