带有 Google Cloud Endpoints 和 Guice 的 Appengine [英] Appengine with Google Cloud Endpoints and Guice

查看:24
本文介绍了带有 Google Cloud Endpoints 和 Guice 的 Appengine的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想在 Appengine 中使用 Guice 和 Cloud Endpoints 来注入我的服务或 daos - 我想这很常见,但我没有找到相关教程.

So i want to use Guice in Appengine with Cloud Endpoints to inject my services, or daos - pretty common I guess, but I found no tutorial for this.

Appengine 文档的官方 Guice 似乎在这里:https://github.com/google/guice/wiki/GoogleAppEngine

Official Guice for Appengine documentation seems to be here: https://github.com/google/guice/wiki/GoogleAppEngine

在配置 Guice 时,您将 com.google.inject.servlet.GuiceFilter 设置为拦截每个请求/*".在某些时候,您必须初始化模块.就像文档说的一个好地方是 ServletContextListener.

When configuring Guice you set up the com.google.inject.servlet.GuiceFilter to intercept every request "/*". And at some point you must initialize the modules. Like the documentation says a good place to do that is a ServletContextListener.

一种特殊的模块是 ServletModules,它将请求路径映射到 Servlet 类,而不是在 web.xml 中执行此操作,您现在可以以编程方式执行此操作.

One special kind of Module are ServletModules, that map request-Paths to Servlet-Classes, instead of doing this in the web.xml you can now do this programmatically.

非常直接,直到这里.但是如何配置 Guice 以包含端点类?

Pretty straight forward up until here. But how do I configure Guice to also include the Endpoint-Classes?

推荐答案

原来有一个 GuiceSystemServiceServletModule 可以处理这个问题.

Turns out there is a GuiceSystemServiceServletModule that handles exactly this.

public class GuiceSSSModule extends GuiceSystemServiceServletModule {

  @Override
  protected void configureServlets() {
    super.configureServlets();

    Set<Class<?>> serviceClasses = new HashSet<Class<?>>();
    serviceClasses.add(MyEndpoint.class);
    serviceClasses.add(AnotherAndpoint.class);
    this.serveGuiceSystemServiceServlet("/_ah/spi/*", serviceClasses);
  }
}

在您的 ServletContextListener 的 Injector 构造中包含此模块:

Include this module in the Injector construction in your ServletContextListener:

public class MyGSCL extends GuiceServletContextListener {

  @Override
  protected Injector getInjector() {
    return Guice.createInjector(new GuiceSSSModule(), new BaseModule());
  }
}

并在您的 web.xml 中使用此侦听器:

and use this listener in your web.xml:

<listener>
   <listener-class>de.mypkg.MyGSCL</listener-class>
</listener>

还要确保在 web.xml 中包含 Guice 过滤器:

Also make sure to include the Guice filter in your web.xml:

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

您的端点将再次在/_ah/api/... 下可用,您可以在端点类中使用 @Inject.

Your endpoints will be available under /_ah/api/... again and you can use @Inject in your endpoint classes.

这篇关于带有 Google Cloud Endpoints 和 Guice 的 Appengine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆