Reputation: 1302
I need to access to an instance provided via Guice @Provides, so i'm testing a way to access the @Provides Method via a Interceptor...but no way, the interceptor never distpaches. Also i can't change Provider Method Signature , cause inherits from another class ....
public class MyModule extends AbstractModule{
public static class MyInterceptor implements MethodInterceptor{
@Override
public Object invoke(final MethodInvocation methodInvocation) throws Throwable {
System.out.println("MyModule ::: Intercepted@invoke! : "+ methodInvocation.getMethod().getName());
return methodInvocation.proceed();
}
}
@Provides
StampInterface getStamp(){
StampExampleImpl se = new StampExampleImpl();
se.setId("theID");
se.setTst(System.currentTimeMillis());
return se;
}
@Override
protected void configure() {
bindInterceptor(Matchers.any(),
Matchers.annotatedWith(Provides.class),
new MyInterceptor());
}
public static void main(String... args) {
StampInterface s = Guice.createInjector(new MyModule()).getInstance(StampInterface.class);
System.out.println( s.getTst());
System.out.println("---------------------------");
}
}
Upvotes: 0
Views: 1130
Reputation: 11993
Please check the limitations of guice aop as described here: https://github.com/google/guice/wiki/AOP#limitations
Instances must be created by Guice by an @Inject-annotated or no-argument constructor It is not possible to use method interception on instances that aren't constructed by Guice.
You are creating the StampExampleImpl yourself via "new" (doesn't matter that you do so inside a produces method). Thus guice does not know about it in regard to interception.
Quick fix: let guice create the impl instance for you:
@Provides
StampInterface getStamp(StampExampleImpl se){
se.setId("theID");
se.setTst(System.currentTimeMillis());
return se;
}
2nd Problem: why matching on "annotatedWith(Provides)"? You want to intercept the getTsd() method of your StampInterface, and that is not annotated. The annotation is on the producer method of your module, which is a different thing.
Upvotes: 3