搭配 Cloud Endpoints Framework 使用 Guice

Google Guice 是一種相依項目植入架構,可與 Endpoints Frameworks v2 專案搭配使用,以便透過程式輔助方式在 Java 中設定 Servlet 對應與篩選功能,而不是在 web.xml 中設定。

如要使用 Guice,您必須在 pom.xmlbuild.gradle 中新增以下預先封裝的相依項目。此外,您還需要設定適用於 Maven 和 Gradle 的 Endpoints Frameworks 外掛程式,藉此定義外掛程式要使用哪個服務類別來建立 OpenAPI 文件。

MavenGradle

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

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/* 的所有流量導向 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>

在專案中實作事件監聽器類別。視服務的數量而定,它看起來應該會如下所示:

public class EchoGuiceListener extends GuiceServletContextListener {

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

事件監聽器類別會建立一個新的插入程式,用於處理 Servlet 對應和篩選功能,這通常由 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));
  }
}

後續步驟