שימוש ב-Guice עם Cloud Endpoints Frameworks

Google Guice הוא פריימוורק להזרקת תלות שאפשר להשתמש בו עם פרויקט של Endpoints Frameworks v2 כדי להגדיר מיפוי של סרוולטים וסינון באופן פרוגרמטי ב-Java, במקום ב-web.xml.

כדי להשתמש ב-Guice, צריך להוסיף את יחסי התלות הבאים שכלולים מראש ל-pom.xml או ל-build.gradle. בנוסף, צריך להגדיר את התוספים של Endpoints Frameworks ל-Maven ול-Gradle כדי להגדיר אילו מחלקות שירות התוספים משתמשים בהן כדי ליצור מסמכי OpenAPI.

Maven

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

Gradle

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

בשלב הבא, צריך לעדכן את web.xml כדי להפנות את כל התעבורה מ-/_ah/api/* אל Guice Servlet של Endpoints Frameworks.

<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>

מטמיעים את מחלקת ה-listener בפרויקט. הוא אמור להיראות כמו אחת מהדוגמאות הבאות, בהתאם למספר השירותים:

public class EchoGuiceListener extends GuiceServletContextListener {

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

מחלקת המאזין יוצרת מזרק חדש שמטפל במיפוי ובסינון של סרוולטים, שבדרך כלל מוגדרים על ידי web.xml, אבל עכשיו מוגדרים על ידי המחלקה EchoEndpointModule באופן הבא:

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<>();
    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));
  }
}

מה השלב הבא?