Search code examples
javadependency-injectionguice

Deferred binding to instance using Guice


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.


Solution

  • use Provider,

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

    check this

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