I want to secure a google cloud endpoint with a custom com.google.api.server.spi.config.Authenticator. see this post (Google Cloud Endpoints and user's authentication). For example to authenticate via facebook oauth. The Authenticator must have a default constructor without any params otherwise the Authenticator does not work. So Constructor Injection is not possible like this:
@Inject
public apiMethod(Log logger, Datastore datastore, MemCacheManager cacheManager) {
this.logger = logger;
this.datastore = datastore;
this.cacheManager = cacheManager;
}
I want to cache some data in the Authenticator. So I need an instance of memcachemanager and the logger for logs. Does anyone has an idea how Injection can be done without constructor injection?
Thanks! Smilingm
I don't know about Google Cloud Endpoints, but I do know about Guice. I have suspicion that you're not going to get the answer you want here, so I'll provide a quick roundup of what I know.
Ultimately, the code which will call your
Authenticator
either needs to be injected itself or have access to an injector, and know to either callInjector.injectMembers(yourAuthenticator)
after instantiating it (presumably with the no-arg constructor you're required to provide) or to construct yourAuthenticator
by having it injected or requesting it from theInjector
.Given that your
Authenticator
needs to have a specific constructor signature, it seems pretty likely that the caller isn't using injection here, but this page implies that methods annotated with@ApiMethod
can have named parameters injected, so maybe it'll work. You can test this pretty quickly by trying field injection:If that doesn't work, then it's time to grumble. It'd be nice if Google supported their own DI framework here. DI only works if the full stack supports it. If your entry point doesn't use injection, then you will be forced to take alternative measures such as putting your
Injector
in a global singleton, which is missing the point of DI, or constructing your dependencies yourself. Sometimes this sort of pain is unavoidable.Edit: As indeed it sounds like there's no Guice injection happening after instantiation of an
Authenticator
, yourAuthenticator
will only have the option of getting its dependencies from static scope or constructing them directly. You won't be able to use Guice.