My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
InstanceBindings  
Updated Oct 16, 2011 by sberlin

Instance Bindings

You can bind a type to a specific instance of that type. This is usually only useful only for objects that don't have dependencies of their own, such as value objects:

    bind(String.class)
        .annotatedWith(Names.named("JDBC URL"))
        .toInstance("jdbc:mysql://localhost/pizza");
    bind(Integer.class)
        .annotatedWith(Names.named("login timeout seconds"))
        .toInstance(10);

Avoid using .toInstance with objects that are complicated to create, since it can slow down application startup. You can use an @Provides method instead.

Comment by martin.d...@gmail.com, Aug 26, 2009

This is not a very helpful example, what is Names.named??

Comment by nickgies...@gmail.com, Nov 3, 2009

@martin, c.f. @Named in previous section

Comment by thang...@gmail.com, Apr 22, 2010

I am not sure why instance binding is not useful.

I can do this in BillingModule?:

Injector injector = Guice.createInjector(new DatabaseTransactionLogModule?());

TransactionLog? dbTransLog = njector.getInstance(DatabaseTransactionLog?.class);

bind(TransactionLog??.class).toInstance(dbTransLog);

With @provider, I am not sure whether you can pass Guice injected DatabaseTransactionLog? instance to BillingService? instance or not.

Comment by philippe.beaudoin, Mar 17, 2011

An example of bindConstant() would be helpful in the doc around here...

Comment by alexande...@gmail.com, May 8, 2012

I'm using this to get different Cache objects from an Ehcache manager and I'm now wondering if .toInstance() would slow down anything. I could perfectly use it on the other hand to implement dynamic cache creation (based on my configuration properties).


Sign in to add a comment
Powered by Google Project Hosting