我正在尝试打印"Hello,AOP!" 每当Guice/AOP联盟拦截标有特定(自定义)注释的方法时,就会发出消息.我已经按照官方文档(可在此处找到的PDF - 第11页的AOP方法拦截内容))并且不能让它工作,只能编译.
首先,我的注释:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@BindingAnnotation
public @interface Validating {
// Do nothing; used by Google Guice to intercept certain methods.
}
Run Code Online (Sandbox Code Playgroud)
然后,我的Module实施:
public class ValidatingModule implements com.google.inject.Module {
public void configure(Binder binder) {
binder.bindInterceptor(Matchers.any(),
Matchers.annotatedWith(Validating.class,
new ValidatingMethodInterceptor()),
}
}
Run Code Online (Sandbox Code Playgroud)
接下来,我的方法拦截器:
public class ValidatingMethodInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("Hello, AOP!");
}
}
Run Code Online (Sandbox Code Playgroud)
最后,尝试使用所有这些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();
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行这个小测试驱动程序时,我得到的唯一控制台输出是About to use AOP......... Hello, AOP!永远不会被执行,这意味着该@Validating doSomething()方法永远不会像Guice文档显示的那样被截获.
该只有我能想到的事情是,在我的事实Module执行我指定MethodInterceptor绑定到(作为第三个参数的bindInterceptor方法)为一个new ValidatingMethodInterceptor(),而在拦截器,一个需要我只界定invoke(MethodInvocation)方法.
也许我没有正确地将这两者连接在一起?也许Guice没有隐含地知道invoke在拦截发生时应该运行该方法?!?!
然后,我不仅跟着Guice文档,我还跟着其他几个教程无济于事.
我有什么明显的遗失吗?提前致谢!
编辑我的代码和我遵循的示例之间的另一个差异,虽然很小,但是我的invoke方法(在拦截器内)没有注释@Override.如果我尝试添加此注释,我会收到以下编译错误:
ValidatingMethodInterceptor类型的方法invoke(MethodInvocation)必须覆盖超类方法.
这个错误是有道理的,因为它org.aopalliance.intercept.MethodInterceptor是一个接口(不是一个类).然后,每个使用Guice/AOP联盟的例子都@Override在这个invoke方法上使用这个注释,所以它显然可以为一些人工作/编译......很奇怪.
JB *_*zet 10
如果你不让Guice构造你的对象,它就不能为你提供一个带有拦截器的实例.您不得使用new AopTest()获取对象的实例.相反,你必须要求Guice给你一个例子:
Injector injector = Guice.createInjector(new ValidatingModule ());
AopTest test = injector.getInstance(AopTest.class);
Run Code Online (Sandbox Code Playgroud)
请参阅http://code.google.com/p/google-guice/wiki/GettingStarted
| 归档时间: |
|
| 查看次数: |
4452 次 |
| 最近记录: |