How to set up Swagger in Glassfish 4 without web.xml?

The Swagger documentation contains several different ways to configure Swagger in an application. Unfortunately, they all use web.xml and rely on hard coding the api version and base url in web.xml

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

+4
source share
1 answer

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

  • Includes the following dependency in the gradle assembly file (this approach also applies to Maven):

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

  • , javax.ws.rs.core.Application ApplicationPath, .

    @ApplicationPath ( "" ) RESTConfig {}

2. , 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);
    }
  }
} 
+8

All Articles