gpt4 book ai didi

java - 无法让 Guice 方法拦截工作

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:49:53 24 4
gpt4 key购买 nike

我正在尝试打印“Hello, AOP!”每当 Guice/AOP Alliance 截获标有特定(自定义)注解的方法时,就会发出消息。我遵循了官方文档(可以找到的 PDF here - 第 11 页上的 AOP 方法拦截内容)但无法让它工作,只能编译。

首先,我的注释:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@BindingAnnotation
public @interface Validating {
// Do nothing; used by Google Guice to intercept certain methods.
}

然后,我的Module实现:

public class ValidatingModule implements com.google.inject.Module {
public void configure(Binder binder) {
binder.bindInterceptor(Matchers.any(),
Matchers.annotatedWith(Validating.class,
new ValidatingMethodInterceptor()),
}
}

接下来,我的方法拦截器:

public class ValidatingMethodInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("Hello, AOP!");
}
}

最后,尝试使用所有这些 AOP 内容的驱动程序:

public class AopTest {
@Validating
public int doSomething() {
// do whatever
}

public static main(String[] args) {
AopTest test = new AopTest();

Injector injector = Guice.createInjector(new ValidatingModule());

System.out.println("About to use AOP...");

test.doSomething();
}
}

当我运行这个小测试驱动程序时,我得到的唯一控制台输出是 About to use AOP... ... Hello, AOP!永远不会被执行,这意味着 @Validating doSomething()方法永远不会像 Guice 文档显示的那样被拦截。

唯一我能想到的是在我的 Module 中实现我指定 MethodInterceptor绑定(bind)到(作为 bindInterceptor 方法的第三个参数)作为 new ValidatingMethodInterceptor() ,而在那个拦截器中,我只定义了一个必需的 invoke(MethodInvocation ) 方法。

也许我没有正确地将这两者连接在一起?也许 Guice 并不知道 invoke发生拦截时应该运行方法?!?!

话又说回来,我不仅遵循了 Guice 文档,而且还遵循了其他几个教程,但都无济于事。

我在这里明显遗漏了什么吗?提前致谢!

编辑 我的代码和我遵循的示例之间的另一个差异虽然很小,但事实上我的 invoke方法(在拦截器内部)未用 @Override 注释.如果我尝试添加此注释,则会出现以下编译错误:

The method invoke(MethodInvocation) of type ValidatingMethodInterceptor must override a superclass method.

这个错误是有道理的,因为org.aopalliance.intercept.MethodInterceptor是一个接口(interface)(不是类)。再一次,每个使用 Guice/AOP Alliance 的例子都使用这个 @Override invoke 上的注释方法,所以它显然对某些人有效/编译...很奇怪。

最佳答案

如果您不让 Guice 构造您的对象,它就无法为您提供一个包含拦截器的实例。您不得使用 new AopTest() 来获取对象的实例。相反,您必须要求 Guice 给您一个实例:

Injector injector = Guice.createInjector(new ValidatingModule ());
AopTest test = injector.getInstance(AopTest.class);

参见 http://code.google.com/p/google-guice/wiki/GettingStarted

关于java - 无法让 Guice 方法拦截工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8862531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com