Using Guice with Endpoints Frameworks

Google Guice is a dependency injection framework that you can use with an Endpoints Frameworks v2 project to configure servlet mapping and filtering programmatically in Java, rather than in web.xml.

To use Guice, you need to add the following prepackaged dependency to your pom.xml or build.gradle. The Endpoints Framework plugins for Maven and Gradle also need to be configured to define which service classes the plugins will use to create OpenAPI documents.

Maven

<dependency>
    <groupId>com.google.endpoints</groupId>
    <artifactId>endpoints-framework-guice</artifactId>
    <version>2.0.14</version>
</dependency>

Gradle

compile 'com.google.endpoints:endpoints-framework-guice:2.0.9'
endpointsServer {
  // Endpoints Framework Plugin server-side configuration
  hostname = "${projectId}.appspot.com"
  serviceClasses = ['com.example.echo.Echo']
}

Next, you need to update web.xml to direct all traffic from /_ah/api/* to the Endpoints Framework Guice Servlet.

<filter>
    <filter-name>guiceFilter</filter-name>
    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>

<!--
  URL Pattern /_ah/api/* instead of /* because a legacy v1 servlet uses
  the route /_ah/api/ and using /* will erronously use the legacy v1
  servlet instead of routing to your API.
-->
<filter-mapping>
    <filter-name>guiceFilter</filter-name>
    <url-pattern>/_ah/api/*</url-pattern>
</filter-mapping>

<listener>
    <listener-class>com.example.echo.EchoGuiceListener</listener-class>
</listener>

The listener class needs to be implemented in your project and should look similar to the following depending on the number of services.

public class EchoGuiceListener extends GuiceServletContextListener {

  @Override
  protected Injector getInjector() {
    return Guice.createInjector(new EchoEndpointModule());
  }
}

The listener class creates a new injector that handles servlet mapping and filtering, which is normally defined by the web.xml, but instead is now defined by the EchoEndpointModule class defined as:

public class EchoEndpointModule extends EndpointsModule {
  @Override
  public void configureServlets() {
    super.configureServlets();

    bind(ServiceManagementConfigFilter.class).in(Singleton.class);
    filter("/_ah/api/*").through(ServiceManagementConfigFilter.class);

    Map<String, String> apiController = new HashMap<String, String>();
    apiController.put("endpoints.projectId", "YOUR-PROJECT-ID");
    apiController.put("endpoints.serviceName", "YOUR-PROJECT-ID.appspot.com");

    bind(GoogleAppEngineControlFilter.class).in(Singleton.class);
    filter("/_ah/api/*").through(GoogleAppEngineControlFilter.class, apiController);

    bind(Echo.class).toInstance(new Echo());
    configureEndpoints("/_ah/api/*", ImmutableList.of(Echo.class));
  }
}

What's Next?

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Endpoints Frameworks for App Engine