【发布时间】:2020-09-12 10:36:34
【问题描述】:
我正在构建一个包,它试图根据标志截取函数的返回值。我的设计涉及一些 AOP。这个想法是一个类FirstIntercept拦截一个调用firstCall并将参数存储在Parameters对象中。然后稍后,第二个类 SecondIntercept 拦截另一个调用 secondCall 并根据 Parameters 中填充的内容执行一些逻辑:
// pseudoish code
public class FirstIntercept {
private Parameters param;
@AfterReturning(pointcut = "execution(* ...firstCall(..))", returning = "payload")
public void loadParam(Joinpoint joinPoint, Object payload) {
// logic handling payload returned from firstCall()
// logic provides a Boolean flag
this.param = new Parameters(flag);
}
}
public class Parameters {
@Getter
private Boolean flag;
public Parameters(Boolean flag) {
this.flag = flag;
}
}
public class SecondIntercept {
private static Parameters params;
@Around("execution(* ...secondCall(..))")
public void handleSecondCallIntercept(ProceedingJoinPoint joinPoint) {
// want to do logic here based on what params contains
}
}
我想要实现的是Parameters 对象在通过AOP 调用FirstIntercept.loadParam 时一劳永逸地加载。我不太确定我该如何坚持这种坚持。我在网上看了看,Google guice 似乎很有希望。我相信第一步是在Parameters 上使用依赖注入,但我真的不确定。有人可以帮我指出正确的方向吗?
编辑:
所以我尝试了这个设置:
public class FirstIntercept implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("invoked!");
return invocation.proceed();
}
@AfterReturning(pointcut = "execution(* ...firstCall(..))", returning = "payload")
public void loadParam(Joinpoint joinPoint, Object payload) {
// do stuff
}
public String firstCall() {
return "hello";
}
}
public class InterceptionModule extends AbstractModule {
protected void configure() {
FirstIntercept first = new FirstIntercept();
bindInterceptor(Matchers.any(), Matchers.annotatedWith(AfterReturning.class), first);
}
}
public class FirstIterceptTest {
@Test
public void dummy() {
Injector injector = Guice.createInjector(new InterceptionModule());
FirstIntercept intercept = injector.getInstance(FirstIntercept.class);
intercept.firstCall();
}
}
当我执行.firstCall() 时,我可以看到@AfterReturning 正在运行,但没有调用调用。
【问题讨论】: