【问题标题】:Initialize swagger without web.xml to disable it in production在没有 web.xml 的情况下初始化 swagger 以在生产中禁用它
【发布时间】:2017-08-03 13:01:52
【问题描述】:

我将 Swagger 与 Jersey 2 和 spring bootstrap 一起使用。目前我正在寻找一种解决方案来禁用生产中的招摇,因为如果任何用户都会担心 将 API 与 swagger UI 一起使用。

我在 web.xml 中注册 io.swagger.jersey.config.JerseyJaxrsConfig servlet 并将初始化参数传递给它,如 api.version 和 swagger.api.basepath。除此之外,我正在注册要扫描为 io.swagger.jaxrs.listing 的包,以便 org.glassfish.jersey.server.ResourceConfig 会注意准备 swagger UI。

我从互联网上了解到,我们可以使用 @profile 注释来实现这一目标。但我经历过,如果我们在 Web.xml 中注册任何类,即使您在该类级别上使用 @Profile,它也不会工作,因为该类将在上下文加载时加载。

我的项目中有静态内容,例如 swagger-ui-min.js、swagger-ui.js、index.html 等来加载 swagger。

使用此设置,如何在生产环境中禁用 Swagger UI?另外,如果有人有经验,是否应该在生产中禁用 swagger?

【问题讨论】:

    标签: rest jersey-2.0 swagger-ui


    【解决方案1】:

    你可以有一个标志,它只允许在你不生产时加载 Swagger Servlet(这里是 Swagger 2):

    import javax.ws.rs.ApplicationPath;
    import javax.ws.rs.core.Application;
    import java.util.HashSet;
    import java.util.Set;
    import io.swagger.jaxrs2.integration.resources.OpenApiResource;
    
    @ApplicationPath("") // no application path after the context root
    public class MyApp extends Application {
        @Override
        public Set<Class<?>> getClasses() {
            Set<Class<?>> classes = new HashSet<>();
            classes.add(...); // your main service
            if (notInProduction) { // a flag telling that you are not in production
                classes.add(OpenApiResource.class);
            }
            return classes;
        }
    }
    

    【讨论】:

    • 是的,这是在环境变量的帮助下排序的。我只是在环境变量设置为开发的情况下注册了 swagger UI 包。对于其他环境,此包将不会被注册。感谢您的回复。
    • 所以你应该提交你的解决方案作为答案并接受它。
    【解决方案2】:

    下面的代码对我有用。

    String enable_swagger_ui = System.getenv("ENABLE_SWAGGER_UI");
     if( enable_swagger_ui != null && enable_swagger_ui.equalsIgnoreCase("true"))
                packages("io.swagger.jaxrs.listing");
    

    您只需在要启用 swagger 的系统环境变量中添加 ENABLE_SWAGGER_UI。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 2019-04-23
      相关资源
      最近更新 更多