optional injection behaving strangely on a provider in a private module

43 views
Skip to first unread message

dmitrig

unread,
May 26, 2012, 12:22:31 AM5/26/12
to google...@googlegroups.com
Hi,

Can anyone explain why this test fails?  Optional injection points seem to be getting ignored when they occur on a provider inside a private module.  The fact that this passes when you set optional=false leads me to believe that it might be a bug.  Using guice 3.0.

    public static class Foo { 
        public Bar bar;
        Foo(Bar bar) { this.bar = bar; }
    }
    
    static class Bar {  }
    
    static class FooProvider implements Provider<Foo> {
        @Inject(optional=false) public Bar bar;
        public Foo get() {
            return new Foo(bar);
        }
    }

    static class ChildInjectorInjector {
        public Injector injector;
        @Inject
        ChildInjectorInjector(Injector injector) {
            this.injector = injector;
        }
    }
    
    
    @Test
    public void test() throws Exception {
            Injector i = Guice.createInjector(new PrivateModule() {
                @Override protected void configure() {
                        bind(Bar.class);
                        bind(Foo.class).toProvider(FooProvider.class);
                        bind(ChildInjectorInjector.class);
                        expose(ChildInjectorInjector.class);
                    }
                });
        Injector ci = i.getInstance(ChildInjectorInjector.class).injector;
        Foo foo = ci.getInstance(Foo.class);
        assertTrue(foo.bar != null);
    }

dmitrig

unread,
May 26, 2012, 12:29:36 AM5/26/12
to google...@googlegroups.com
Sorry, that should be

 @Inject(optional=true) public Bar bar;

dmitrig

unread,
May 26, 2012, 1:07:47 AM5/26/12
to google...@googlegroups.com
Sorry, here's a less nonsensical test case:

    
    static class Foo { 
        public Bar bar;
        Foo(Bar bar) { this.bar = bar; }
    }
    
    static class Bar {  }
    
    static class FooProvider implements Provider<Foo> {
        @Inject(optional=true) public Bar bar;
        public Foo get() {
            return new Foo(bar);
        }
    }
    
    @Test
    public void test() throws Exception {
        Injector i = Guice.createInjector(new PrivateModule() {
            @Override
            protected void configure() {
                bind(Bar.class);
                bind(Foo.class).toProvider(FooProvider.class);
                expose(Foo.class);
            }
        });
        Foo foo = i.getInstance(Foo.class);
        assertTrue(foo.bar != null);
    }
Reply all
Reply to author
Forward
0 new messages