Search code examples
guiceswaggerguice-servlet

Swagger and Google Guice setup


I'm trying to add swagger to my project. Our setup differs a bit from the sample projects. We use guice and guice-servlet to inject and start our JerseyServletModule.

Today our web.xml looks something like this

<web-app ....>
    <listener>
        <listener-class>com.mypackage.MyServletModule</listener-class>
     </listener>
    <filter>
        <filter-name>guiceFilter</filter-name>
        <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>guiceFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

And the class MyServletModule looks like

public class MyServletModule extends GuiceServletContextListener {
  ...
  @Override
  protected Injector getInjector() {
  JerseyServletModule api = new JerseyServletModule() {
      @Override
      protected void configureServlets() {
        ... 
        bind().to()
        ... 
        serve("/api/v1/*").with(GuiceContainer.class);
        }
      };
    return Guice.createInjector(api);
  }
}

Where and how should I add swagger?


Solution

  • You need to tell Jersey where to find the Swagger resources like this (where org.example is your package containing services):

    Map<String, String> params = Maps.newHashMap();
    params.put(PackagesResourceConfig.PROPERTY_PACKAGES, "org.example;com.wordnik.swagger.jaxrs.listing");
    serve("/api/v1/*").with(GuiceContainer.class, params);
    

    Also be sure that Swagger is on your classpath. If you're using Maven add:

    <dependency>
      <groupId>com.wordnik</groupId>
      <artifactId>swagger-jaxrs_2.9.1</artifactId>
      <version>1.2.1</version>
      <scope>compile</scope>
    </dependency>