5

The Swagger documentation covers a number of different ways to configure Swagger in an application. Unfortunately all of them leverage web.xml and rely on hard coding the api version and base url in the web.xml

Is there a way to configure Swagger without using a web.xml and without hardcoding the api version and base path?

4

1 回答 1

9

我使用以下方法在没有资源 XML 的 Glassfish 4 中配置 Swagger。

  1. 在 gradle 构建文件中包含以下依赖项(此方法也适用于 Maven):

    编译('com.wordnik:swagger-jaxrs_2.9.1:1.3.0'){排除组:'org.scala-lang',模块:'scala-compiler'}

  2. 创建一个扩展 javax.ws.rs.core.Application 的类并配置 ApplicationPath,例如

    @ApplicationPath("resources") 公共类 RESTConfig 扩展应用程序 {}

2a. 创建一个扩展 com.wordnik.swagger.jaxrs.config.DefaultJaxrsConfig 的类并注解如下:

@WebServlet(name = "SwaagerJaxrsConfig" initParams = {@WebInitParam(name="api.version",  value="0.1.0"), @WebInitParam(name="swagger.api.basepath", value="http://localhost:8080/resources"})}, loadOnStartup = 2) 

public class SwaagerJaxrsConfig  extends DefaultJaxrsConfig{}

这种方法的缺点是您的应用程序的 api 版本和基本 url 被硬编码在注释中。为了解决这个问题,我使用了以下方法而不是上面的方法

2b。创建一个扩展 HttpServlet 并执行由 DefaultJaxrsConfig 完成的引导的类,例如

@WebServlet(name = "SwaggerJaxrsConfig", loadOnStartup = 2)
public class SwaggerJaxrsConfig extends HttpServlet {

private Logger log = Logger.getLogger(SwaggerJaxrsConfig.class);

@Inject Version version;

@Override public void init(ServletConfig servletConfig) {
    try {
        super.init(servletConfig);
        SwaggerConfig swaggerConfig = new SwaggerConfig();
        ConfigFactory.setConfig(swaggerConfig);
        swaggerConfig.setBasePath("http://localhost:8080/resources"); //TODO look up app path
        swaggerConfig.setApiVersion(version.getVersion());
        ScannerFactory.setScanner(new DefaultJaxrsScanner());
        ClassReaders.setReader(new DefaultJaxrsApiReader());
    } catch (Exception e) {
        log.error("Failed to configure swagger", e);
    }
  }
} 
于 2013-10-29T17:13:50.190 回答