我想使用自定义的com.google.api.server.spi.config.Authenticator保护Google云端点。
请参阅这篇文章(Google Cloud Endpoints and user's authentication)。
例如,通过facebook oauth进行身份验证。
Authenticator必须具有不带任何参数的默认构造函数,否则Authenticator无法正常工作。因此,构造函数注入(inject)不可能像这样:

@Inject
public apiMethod(Log logger, Datastore datastore, MemCacheManager cacheManager) {
        this.logger = logger;
        this.datastore = datastore;
        this.cacheManager = cacheManager;
}

我想在身份验证器中缓存一些数据。因此,我需要一个memcachemanager实例和一个日志记录器。有谁知道如何在没有构造函数注入(inject)的情况下完成注入(inject)?

谢谢!
笑脸

最佳答案

我不了解Google Cloud Endpoints,但我了解Guice。我怀疑您不会在这里得到想要的答案,因此我将快速汇总我所知道的内容。

最终,调用Authenticator的代码要么需要自身注入(inject),要么可以访问注入(inject)器,并知道在实例化后调用Injector.injectMembers(yourAuthenticator)(大概是需要提供的无参构造函数)或构造您的通过将Authenticator注入(inject)或从Injector请求它。

鉴于您的Authenticator需要具有特定的构造函数签名,调用者似乎很可能不在此处使用注入(inject),但是this page意味着以@ApiMethod注释的方法可以注入(inject)已命名的参数,因此也许可以使用。您可以尝试进行现场注入(inject),从而相当快速地进行测试:

@Inject private Log logger;
@Inject private Datastore datastore;
@Inject private MemCacheManager cacheManager;

如果那不起作用,那就该抱怨了。如果Google在这里支持自己的DI框架,那就太好了。 DI仅在完整堆栈支持的情况下才有效。如果您的入口点不使用注入(inject),那么您将被迫采取其他措施,例如将Injector放在全局单例中,即missing the point of DI,或者自己构建依赖项。有时这种痛苦是不可避免的。

编辑:确实,听起来像在实例化Authenticator之后没有进行Guice注入(inject),您的Authenticator将只能选择从静态范围获取其依赖项或直接构造它们。您将无法使用Guice。

关于dependency-injection - 在Google Cloud Endpoints的自定义身份验证器中使用Guice Injection,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32840413/

10-10 04:04