将 Guice 与 Cloud Endpoints Frameworks 搭配使用

Google Guice 是一种依赖项注入框架,可与 用于配置 servlet 映射和过滤的 Endpoints Frameworks v2 项目 使用 Java 编程, web.xml

要使用 Guice,您需要将以下预封装依赖项添加到 pom.xmlbuild.gradle。此外,您还需要配置适用于 Maven 和 Gradle 的 Endpoints Frameworks 插件,以定义这些插件将使用哪些服务类来创建 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/* 导向 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));
  }
}

后续步骤