user3201336
user3201336

Reputation: 255

Google Guice return new instance every time

I am newbie to Dependency Injection and had to learn both Spring and Guice recently. The question below may be pretty lame.

Spring lets you create prototype objects with @Scope("prototype") annotation meaning a new object is returned every time

Eg in my spring container:-

@Scope("prototype")
@Bean
A getA(){
   return new A();
}

And a new object A is injected in all references of @autowired.

class B {
  @Autowired
  A objA;
}

However, in guice injector, the same instance is being injected. Looks like guice provides only singleton, request or session scopes https://github.com/google/guice/wiki/Scopes. My application is not exactly a web service and am wondering how to inject new instances of the object everywhere. I read provider could be used, but couldn't find any lame/easy examples to understand.

How could I inject new instances of A into B or any other class? With Guice, currently I am able to inject only same instance with all classes like below in guice container

bind(A.Class).toInstance(new A());
new B(); // or create with other ways 

Upvotes: 4

Views: 10650

Answers (2)

Olivier Grégoire
Olivier Grégoire

Reputation: 35407

Just use no binding

The default binding creates a new instance everytime it is injected.

You don't need to declare anything:

import com.google.inject.*;

class Main {
  static class B {
    @Inject A a;
  }
  public static void main(String[] args) {
    Injector injector = Guice.createInjector();
    B b1 = injector.getInstance(B.class);
    B b2 = injector.getInstance(B.class);

    System.out.println(b1.a == b2.a); // Prints "false"
  }
}

Upvotes: 1

Jan Galinski
Jan Galinski

Reputation: 11993

The desired behavior is the default of guice, so you get a new instance every time, unless you explicitly switch to singleton.

And thats what you do when you bind toInstance. You are telling guice "eyery time someone needs a instance of A, give him this one (the one created via 'new'".

If you just want to get a new A injected whenever you build a B, do not specify any behavior in the module, just let A have a constructor annotated with @Inject.

Upvotes: 7

Related Questions