6

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?

lucasweb
  • 1,736
  • 5
  • 28
  • 42

1 Answers1

10

I used the following approach to configure Swagger in Glassfish 4 without a resource XML.

  1. Includes the following dependency in by gradle build file (this approach also applies to Maven):

    compile ('com.wordnik:swagger-jaxrs_2.9.1:1.3.0') { exclude group: 'org.scala-lang', module: 'scala-compiler' }

  2. Create a class that extends javax.ws.rs.core.Application and configure the ApplicationPath e.g.

    @ApplicationPath("resources") public class RESTConfig extends Application {}

2a. Create a class that extends com.wordnik.swagger.jaxrs.config.DefaultJaxrsConfig and annotate as follows:

@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{}

The downside of this approach is that the api version and base url of your app is hardcoded in the annotation. In order to get around this I used the following approach instead of the one above

2b. Create a class that extends HttpServlet and performs the bootstrapping done by DefaultJaxrsConfig e.g.

@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);
    }
  }
} 
lucasweb
  • 1,736
  • 5
  • 28
  • 42
  • 1
    thanks for the answer! It would be super helpful to the community if you happen to have a git url and could share as there are multiple steps in the answer with different classes – user2359997 Jan 06 '20 at 00:45