你如何在生产中关闭swagger-ui

use*_*693 31 java spring swagger swagger-ui spring-boot

我已经将swagger插入我的春季启动应用程序.Spring启动允许您拥有每个环境的属性文件.有没有办法禁用生产环境的招摇?

lub*_*nac 25

将您的swagger配置放入单独的配置类中,并使用@Profile注释 - > 对其进行注释,以便仅在某些配置文件中将其扫描到Spring上下文中.

例:

@Configuration
@EnableSwagger2
@Profile("dev")
public class SwaggerConfig {
    // your swagger configuration
}
Run Code Online (Sandbox Code Playgroud)

您可以通过命令行定义Spring Boot应用程序运行的--spring.profiles.active=dev配置文件:或通过配置文件:spring.profiles.active=dev.

阅读Spring Boot文档的这一部分以获取更多信息 @Profile

  • 我们已经这样做了,看起来扩展 - > swagger-ui.html仍然出现,即使api的内容没有显示.有没有办法让它变得如此swagger-ui.html甚至不会产生? (8认同)
  • 我知道这是一个老问题,但是我们使用@Profile(“!prod”)避免显式指定大量其他配置文件。希望它能帮助到别人。 (3认同)
  • @ user301693如果您使用的是Maven,则可以在特定的Maven配置文件中加载swagger依赖项,这应该可以解决我的问题。 (2认同)
  • @ g00glen00b,PROD的工件与其他环境不同?我猜QA和OPS的家伙会对此不满意. (2认同)
  • /sf/ask/3251813141/ (2认同)

Per*_*vez 20

如果您正在处理多个环境,那么您也可以使用@Profile作为数组

@Configuration
@EnableSwagger2
@Profile({"dev","qa"})
public class SwaggerConfig {
   // your swagger configuration
}
Run Code Online (Sandbox Code Playgroud)


小智 10

使用swagger 3.0.0版本,您可以springfox.documentation.enabled=false在相应的环境配置application.properties文件中添加。例如,我已将其添加到application-prod.properties生产中以禁用(运行应用程序时,您必须使用 VM args 指定配置文件,例如-Dspring.profiles.active=prod


use*_*453 5

这是我的配置类:

@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();
    }
}
Run Code Online (Sandbox Code Playgroud)

无论我在哪里需要 Swagger,我都会将配置文件添加swagger到环境变量中 SPRING_PROFILES_ACTIVE

  • 这基本上重复了[另一个更旧的答案](/sf/answers/2645774771/)(即“使用配置文件”) (2认同)
  • /swagger-ui.html 仍然可用,但没有方法。有没有办法禁止URL? (2认同)