在没有 web 的情况下初始化 swagger .xml以在生产中禁用它



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

我正在web中注册io.swagger.jersey.config.JerseyJaxrsConfig servlet.xml并将init参数传递给它,如api.version和swagger.api.basepath。与此同时,我正在注册要扫描的包作为io.swagger.jaxrs.list,以便org.glassfish.jersey.server.ResourceConfig将注意准备招摇的UI。

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

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

通过此设置,如何在生产中禁用招摇的 UI?另外,如果有人有这方面的经验,是否应该在生产中禁用招摇?

你可以有一个标志,它允许只在你不在生产环境中加载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;
}
}

下面的代码对我有用。

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。

最新更新