为了在guice中实现AOP,我们需要引入aopalliance.jar,AOP Alliance(http://aopalliance.sourceforge.net/)是一套标准AOP接口(interface),spring也用了。
import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; public class ServiceInterceptor implements MethodInterceptor { public Object invoke(MethodInvocation mi) { System.out.println("before"); Object obj = null; try { obj = mi.proceed(); } catch (Throwable t) { } System.out.println("after"); return obj; } }
我们实现MethodInterceptor接口,实现自己的方法拦截器,在invoke()方法中首先打印before,然后通过mi.proceed()调用被拦截方法,调用之后after,最后返回被拦截方法的返回结果。
现在我们将这个方法拦截器配置到Module中,让它拦截所有类的所有方法,只要是guice负责注入的类都会被它拦截。
看一下Main.java中的代码。
import com.google.inject.*; import static com.google.inject.matcher.Matchers.*; public class Main { @Inject private Service service; public static void main(String[] args) { Main main = Guice.createInjector(new Module() { public void configure(Binder binder) { binder.bindInterceptor( any(), any(), new ServiceInterceptor()); } }).getInstance(Main.class); main.service.hello(); } }
配置aop要使用bindInterceptor(),它有三个参数,第一个参数是上面静态导入的Matchers类的any()方法,意思是拦截所有类,第二个参数相似,意思是拦截所有方法,第三个参数就是我们刚刚自定义的方法拦截器。
这样我们从guice中获得Main.class和它包含的service都会被这个拦截器控制住了,调用main.service.hello()可以看到一下结果。
before
hello
after
例子:08-01。