1

I have this in my module:

@Override
protected void configure() {
    bind(Authenticator.class).toInstance(KerberosAuthenticator.create());
}

And the reason for binding to instance here is because Kerberos authentication needs a bit of initialization like so:

    public static KerberosAuthenticator create() {
    KerberosAuthenticator auth = new KerberosAuthenticator();
    auth.start();
    return auth;
}

This works. I particularly like the fact that it works without noise like factories and providers... Can I somehow defer creating this instance. Obviously the create() method is called at the time I am configuring the binding. In this case the creation is not expensive, but in other cases it may be, or, perhaps, not even needed... I am, somehow, missing it in the Guice docs... Thank you.

AlexeiOst
  • 574
  • 4
  • 13

2 Answers2

1

use Provider,

bind(Authenticator.class) .toProvider(AuthenticatorProvider.class)

check this

https://github.com/google/guice/wiki/ProviderBindings

hunter
  • 3,963
  • 1
  • 16
  • 19
  • Hm, I missed it?... I guess I missed it... This is the answer. Makes it very clean at the point of injection. Thank you very much! – AlexeiOst Apr 25 '19 at 16:58
0

You could simply write a provider method:

@Provides
Authenticator provideAuthenticator() {
  KerberosAuthenticator auth = new KerberosAuthenticator();
  auth.start();
  return auth;
}

This meets your requirement of lazyness because (from the page):

Whenever the injector needs an instance of that type, it will invoke the method.

Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137
  • @Provides is not same as Provider. This is not the right answer. – KitKarson Apr 25 '19 at 23:45
  • @KitKarson It's as good as the other answer. See https://github.com/google/guice/wiki/ProvidesMethods – Olivier Grégoire Apr 25 '19 at 23:50
  • I saw that already. The OP looks for lazy injection. `@Provides` does not do that. Provider is the right way to do it. `@Provides` would be helpful when you need to do something with the object before injection. But it is not lazy. – KitKarson Apr 25 '19 at 23:57
  • @KitKarson The documentation I linked states: "Whenever the injector needs an instance of that type, it will invoke the method." That's the definition of "lazy" – Olivier Grégoire Apr 25 '19 at 23:59