xiaodududu / google-guice

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

bindInterceptor in child injector #390

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago

    @Test
    public void test() {
        TestObject testObject =
Guice.createInjector().createChildInjector(new AbstractModule() {
            protected void configure() {
                bindInterceptor(Matchers.any(), Matchers.any(), new
TestMethodInterceptor());
            }
        }).getInstance(TestObject.class);
        testObject.hello();
    }

    public static class TestObject {
        public void hello() {
            System.out.println("Hello");
        }
    }

    public static class TestMethodInterceptor implements MethodInterceptor {

        public Object invoke(MethodInvocation invocation) throws Throwable {
            throw new UnsupportedOperationException();
        }
    }

the test will println hello, instead of throw
UnsupportedOperationException. I guess the default binding is always fall
back to the parent injector, so the interceptor bind in the child injector
is not picked up. I am not sure this is a issue, or could be fixed. A work
around is to bind(TestObject.class) in the child injector.

Original issue reported on code.google.com by tao...@gmail.com on 15 Jun 2009 at 5:10

GoogleCodeExporter commented 9 years ago
Yup, the binding will be created in the parent injector. You need to add 
bind(TestObject.class) to the child 
injector if that's where you want the binding to live.

Original comment by limpbizkit on 15 Jun 2009 at 3:47

GoogleCodeExporter commented 9 years ago
Many, many issues with child injectors seem to be stemming from JIT bindings 
being
added to the parent injector.  I see the necessity in this for many cases, but I
wonder if there's a way we can help coders ensure code is doing what it wants.

I wonder if solving issue 343 would help.  If users want to be be certain their
bindings are ending up in the right place, they can instruct parent & child 
modules
to disable JIT bindings (with the exception of linked bindings, which should be
pseudo-explicit).  I think that would solve 99% of the confusion surrounding 
child
bindings.

Original comment by sberlin on 15 Jun 2009 at 3:52

GoogleCodeExporter commented 9 years ago
Also I think if we create a child injector, we need to make sure the parent 
injector
is not used directly. Always injector.createChildInjector() to create a dummy 
child
injector to avoid the confusion. Otherwise, a JIT binding in parent injector, 
will
prevent other child injector to bind it explicitly.  I will try to write a blog 
on this.

Original comment by tao...@gmail.com on 18 Jun 2009 at 4:49