Reputation: 630
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.
Upvotes: 1
Views: 251
Reputation: 35477
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.
Upvotes: 0
Reputation: 4183
use Provider,
bind(Authenticator.class) .toProvider(AuthenticatorProvider.class)
check this
https://github.com/google/guice/wiki/ProviderBindings
Upvotes: 1