Method interception does not work if another thread has access to object in constructor
The unit test below reproduces this behavior: ---------------- GuiceAopTest.java --------------- public class GuiceAopTest { @Test public void testGuiceAop(){ Injector injector = Guice.createInjector(new MyModule()); MyService myService = injector.getInstance(MyService.class); Assert.assertTrue("myService.isIntercepted() should return true", myService.isIntercepted()); } }
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface MyAnnotation {} class MyModule extends AbstractModule { @Override protected void configure() { bindInterceptor(Matchers.any(), Matchers.annotatedWith(MyAnnotation.class), new MyInterceptor()); } }
class MyInterceptor implements MethodInterceptor{ @Override public Object invoke(MethodInvocation invocation) throws Throwable { return true; } }
class MyService{ @Inject public MyService() { for(int i=0;i<10;i++){ //this line breaks test Executors.newCachedThreadPool().execute(()->isIntercepted()); } } @MyAnnotation public boolean isIntercepted(){ return false; } }
Source: google/guice