Search code examples
javaguice

How do I reuse an existing instance of an object in Google Guice?


I am new to Google Guice. As of now, it seems that every time a new binding is created, a new object is created. If you have two of the same object as a constructor parameter (or field, etc) in two different classes, how do you reuse first instance of the object as the second object's constructor argument? For example:

public interface MyInterfaceA{
    //Method declarations
}
public class MyClassA implements MyInterfaceA{
    private MyInterfaceC myField;

    @Inject
    public MyClassA(MyInterfaceC myField){
        this.myField = myField;
    }

    //Methods, etc.
}
public interface MyInterfaceB{
    //Method declarations
}
public class MyClassB implements MyInterfaceB{
    private MyInterfaceC myField;

    @Inject
    public MyClassB(MyInterfaceC myField){
        this.myField = myField;
    }

    //Methods, etc.
}
public interface MyInterfaceC{
    //Method declarations
}
public class MyClassC implements MyInterfaceC{

    @Inject
    public MyClassC(){
        //Implementation
    }

    //Methods, etc.
}
public class MyModule extends AbstractModule{
    @Override
    protected void configure(){
        bind(MyInterfaceA.class).to(MyClassA.class);
        bind(MyInterfaceB.class).to(MyClassB.class);
        bind(MyInterfaceC.class).to(MyClassC.class);
    }
}

In this example, I think that MyClassA's constructor is called via Guice with a new instance of MyClassC, and MyClassB's constructor is also called with a new instance of MyClassC. How would I first call MyClassA's constructor with a new instance of MyClassC, but then MyClassB's constructor with that same instance of MyClassC with Guice?


Solution

  • As it is already commented by @njzk2, i am just adding code to the following. Here MyClassC will be provided with same object instance every time when injected.

    public class MyModule extends AbstractModule{
        @Override
        protected void configure(){
            bind(MyInterfaceA.class).to(MyClassA.class);
            bind(MyInterfaceB.class).to(MyClassB.class);
            bind(MyInterfaceC.class).to(MyClassC.class).in(Singleton.class);
        }
    }