vipx / google-guice

Automatically exported from code.google.com/p/google-guice
Apache License 2.0
0 stars 0 forks source link

Guice provides different instances of desired type. #693

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
Code:

===
public static class A {
    B b;
    C c;

    public A() {
        System.out.println("A");
    }

    @Inject
    public void setB(B b) {
        this.b = b;
    }

    @Inject
    public void setC(C c) {
        this.c = c;
    }
}

public static class B {
    A a;
    C c;

    public B() {
        System.out.println("B");
    }

    @Inject
    public void setA(A a) {
        this.a = a;
    }

    @Inject
    public void setC(C c) {
        this.c = c;
    }

    void foo() {
        System.out.println(System.identityHashCode(this.c));
        System.out.println(System.identityHashCode(this.a.c));
    }
}

public static class C {
    A a;
    B b;

    public C() {
        System.out.println("C");
    }

    @Inject
    public void setA(A a) {
        this.a = a;
    }

    @Inject
    public void setB(B b) {
        this.b = b;
    }
}

public static void main(String[] args) {
    Guice.createInjector(new AbstractModule() {
        protected void configure() { }
    }).getInstance(B.class).foo();
}

===

Prints:

===
B
A
C
C
A
false
1741825447
363211825
===

It means:
* classes A and B were instantiated twice
* B and A objects have different references to C

Original issue reported on code.google.com by stepan.k...@gmail.com on 11 Mar 2012 at 3:18

GoogleCodeExporter commented 9 years ago
Typo: foo body must be:

===
    void foo() {
        System.out.println(this.c == this.a.c);
        System.out.println(System.identityHashCode(this.c));
        System.out.println(System.identityHashCode(this.a.c));
    }
===

Original comment by stepan.k...@gmail.com on 11 Mar 2012 at 3:19

GoogleCodeExporter commented 9 years ago
C is not declared as Singleton, isn't it?

Original comment by noctariushtc@googlemail.com on 11 Mar 2012 at 4:07

GoogleCodeExporter commented 9 years ago
No. I was sure classes are singleton by default.

After adding @Singleton annotation, code begins to work as I expected, only one 
instance of each class is created.

Original comment by stepan.k...@gmail.com on 11 Mar 2012 at 4:13

GoogleCodeExporter commented 9 years ago
Jepp that's a bit tricky, I guess bindings are never singleton by default, 
someone please correct me if i'm wrong.

Original comment by noctariushtc@googlemail.com on 11 Mar 2012 at 4:42

GoogleCodeExporter commented 9 years ago
http://code.google.com/p/google-guice/wiki/Scopes

"By default, Guice returns a new instance each time it supplies a value."

Original comment by cgdec...@gmail.com on 11 Mar 2012 at 4:44

GoogleCodeExporter commented 9 years ago

Original comment by cgruber@google.com on 27 Mar 2012 at 6:12