说实话,最简单的方法是简单地通过从来没有从类中调用同一类的其他公共/注解的方法避免这个问题:
public class MyClass {
@MyAnnotation
public void foo() {
doBar();
}
@MyAnnotation
public void bar() {
doBar();
}
private void doBar() {
//doesn't go through interceptor
}
}
如果由于某种原因,这不是一个选项,那么你可以看看这种方法。 AspectJ等更具表现力的AOP库为定义切入点提供了更大的灵活性。
在Guice中,切入点只是一个注释属于由Guice实例化的实例的方法。所以这个逻辑必须被移到拦截器本身。
这样做的一种方法可能是使用ThreadLocal
来跟踪拦截器中的条目。扩展这样的事情可能是一个开始:
public abstract class NonReentrantMethodInterceptor implements MethodInterceptor {
private final ThreadLocal<Deque<Object>> callStack = new ThreadLocal<>();
@Override
public final Object invoke(MethodInvocation invocation) throws Throwable {
Deque<Object> callStack = this.callStack.get();
if (callStack == null) {
callStack = new LinkedList<>();
this.callStack.set(callStack);
}
try {
return invokeIfNotReentrant(callStack, invocation);
} finally {
if (callStack.isEmpty()) {
this.callStack.remove();
}
}
}
private final Object invokeIfNotReentrant(Deque<Object> callStack, MethodInvocation invocation) throws Throwable {
Object target = invocation.getThis();
if (callStack.isEmpty() || callStack.peek() != target) {
//not being called on the same object as the last call
callStack.push(target);
try {
return doInvoke(invocation);
} finally {
callStack.pop();
}
} else {
return invocation.proceed();
}
}
protected abstract Object doInvoke(MethodInvocation invocation) throws Throwable;
}
这个使用一个线程本地堆栈跟踪呼叫到拦截器的堆栈。当最后一次调用这个拦截器的目标是同一个对象时,它调用proceed()
并绕过拦截器。当这是第一次调用拦截器时,或者如果最后一次调用不是针对同一个对象的话,它将应用拦截器。
然后,当拦截器激活时,您想应用的实际逻辑将进入doInvoke()
。
用法示例:
public class NonReentrantTester {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new Module());
MyClass instance = injector.getInstance(MyClass.class);
instance.foo();
}
static class Module extends AbstractModule {
@Override
protected void configure() {
bindInterceptor(Matchers.any(), Matchers.annotatedWith(PrintsFirstInvocation.class),
new PrintsFirstInvocationInterceptor());
}
}
public static class MyClass {
@PrintsFirstInvocation
void foo() {
bar();
}
@PrintsFirstInvocation
void bar() {
}
}
public static class PrintsFirstInvocationInterceptor extends NonReentrantMethodInterceptor {
@Override
protected Object doInvoke(MethodInvocation invocation) throws Throwable {
System.out.println(invocation.getMethod());
return invocation.proceed();
}
}
@BindingAnnotation
@Target({FIELD, PARAMETER, METHOD})
@Retention(RUNTIME)
public @interface PrintsFirstInvocation {
}
}
哇,这是非常整洁。幸运的是,两个第一(也是更优雅)的解决方案不容易获得,但我认为你的建议相当整洁。 –
那么,我的应用程序是结构的方式,因为我只关心过滤第一个请求 @Override public Object invoke(MethodInvocation invocation)throws Throwable this.inProcess.get (),invocation.getMethod()); Integer inProcess = this.inProcess.get(); 尝试if(inProcess == null){this.inProcess.set(1); if(inProcess == null){ return doInvoke(invocation); } else { this.inProcess.set(inProcess + 1); return invocation.proceed();最后{ this.inProcess.set(inProcess); } } –
其中 private final ThreadLocal inProcess = new ThreadLocal (); –