我需要访问通过 Guice @Provides 提供的实例,所以我正在测试一种通过拦截器访问 @Provides 方法的方法...但没办法,拦截器永远不会调度。 我也无法更改 Provider Method Signature ,因为继承自另一个类....
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("---------------------------");
}
}
最佳答案
请检查 guice aop 的限制,如下所述: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.
您正在通过“new”自己创建StampExampleImpl(在生成方法中这样做并不重要)。因此 guice 不知道拦截的情况。
快速修复:让 guice 为您创建 impl 实例:
@Provides
StampInterface getStamp(StampExampleImpl se){
se.setId("theID");
se.setTst(System.currentTimeMillis());
return se;
}
第二个问题:为什么要匹配“annotatedWith(Provides)”?您想要拦截 StampInterface 的 getTsd() 方法,并且该方法没有注释。注释位于模块的生产者方法上,这是另一回事。
关于java - Guice 提供者拦截,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33145539/