我正试着打印一个“你好,AOP!”每当Guice/AOP联盟拦截带有特定(自定义)注释的方法时,都会发出消息。我遵循了官方文档(一个PDF格式,可以在pg上找到这里 - 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 (作为bindInterceptor方法的第三个参数)指定为new ValidatingMethodInterceptor(),而在该拦截器中,我只定义了一个必需的invoke(MethodInvocation方法。
也许我没有把这两条线路正确地连接在一起?也许Guice不知道当发生拦截时应该运行invoke方法?!
再说一遍,我不仅跟踪了Guice文档,而且还学习了其他几个教程,但都没有用。
有什么明显的东西我错过了吗?提前感谢!
编辑我的代码和我所遵循的示例之间的另一个差异(虽然很小)是,我的invoke方法(在拦截器中)没有使用@Override进行注释。如果我试图添加这个注释,就会得到以下编译错误:
类型为ValidatingMethodInterceptor的方法调用(ValidatingMethodInterceptor)必须覆盖超类方法。
这个错误是有意义的,因为org.aopalliance.intercept.MethodInterceptor是一个接口(不是一个类)。再说一遍,使用Guice/AOP联盟的每个示例都在invoke方法上使用这个invoke注释,因此它显然适用于某些people...weird。
发布于 2012-01-14 13:45:17
如果您不让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
https://stackoverflow.com/questions/8862531
复制相似问题