xiaodududu / google-guice

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

createChildInjector injects wrong injector #629

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
After createChildInjector binded class using interface fails to inject right 
injector.

Test case, where last two test cases fails:

package com.google.inject;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class CreateChildInjectorTest {

    private Injector parentI;
    private Injector childI;

    @Before
    public void setUp() {
        parentI = Guice.createInjector(Stage.PRODUCTION);
        childI = parentI.createChildInjector(new AbstractModule() {
            @Override
            protected void configure() {
                bind(String.class).toInstance("fooBar");
                bind(BImpl.class);
                bind(A.class).to(AImpl.class);
            }
        });
    };

    @Test
    public void testChildInjectorB() {
        A a = childI.getInstance(BImpl.class);
        Assert.assertEquals(childI, a.getInjector());
        Assert.assertEquals(parentI, a.getInjector().getParent());
        Assert.assertEquals("fooBar", a.getInjector().getInstance(String.class));
    }

    @Test
    public void testChildInjectorA1() {
        A a = childI.getInstance(A.class);
        Assert.assertEquals(childI, a.getInjector());
        Assert.assertEquals(parentI, a.getInjector().getParent());
        Assert.assertEquals("fooBar", a.getInjector().getInstance(String.class));
    }

    @Test(expected = Throwable.class)
    public void testChildInjectorA2() {
        A a = childI.getInstance(A.class);
        Assert.assertEquals(parentI, a.getInjector());
    }

    public static interface A {
        Injector getInjector();
    }

    static class AImpl implements A {
        private Injector inj;

        @Inject
        public AImpl(Injector inj) {
            this.inj = inj;
        }

        @Override
        public Injector getInjector() {
            return inj;
        }
    }

    static class BImpl extends AImpl {
        @Inject
        public BImpl(Injector inj, String val) {
            super(inj);
        }
    }
}

Original issue reported on code.google.com by marcis.m...@gmail.com on 15 May 2011 at 7:25

GoogleCodeExporter commented 9 years ago
And interestingly, if AImpl contructor have String val parameter (public 
AImpl(Injector inj, String val) {...}) everything works.

Original comment by marcis.m...@gmail.com on 15 May 2011 at 7:28

GoogleCodeExporter commented 9 years ago
This is working as designed. From the createChildInjector Javadoc, 
"Just-in-time bindings created for child injectors will be created in an 
ancestor injector whenever possible." To get your desired behavior, create an 
explicit binding in the child injector's module.

Original comment by limpbizkit on 15 May 2011 at 3:16