利用Guice的Aop实现切面事务管理

canca canca
2011-08-15 03:01
1
0

类似于Spring的声明式事务管理,Guice中也可以很容易的实现,这里我拿Guice+Ibatis举个例子。

 

1. Guice要支持aop,首先我们引入aopalliance.jar。

 

2. 声明自己的事务annotation

 

Java代码   
  1. package com.yingxia.server.common;   
  2.   
  3. import java.lang.annotation.ElementType;   
  4. import java.lang.annotation.Retention;   
  5. import java.lang.annotation.RetentionPolicy;   
  6. import java.lang.annotation.Target;   
  7.   
  8. @Target(ElementType.METHOD)   
  9. @Retention(RetentionPolicy.RUNTIME)   
  10. public @interface Transaction {   
  11. }  

 

3. 声明切面事务拦截器TransactionInterceptor

 

Java代码   
  1. package com.yingxia.server.common;   
  2.   
  3. import org.aopalliance.intercept.MethodInterceptor;   
  4. import org.aopalliance.intercept.MethodInvocation;   
  5.   
  6. public class TransactionInterceptor implements MethodInterceptor {   
  7.   
  8.     @Override  
  9.     public Object invoke(MethodInvocation mi) throws Throwable {   
  10.         Object obj = null;   
  11.         try {   
  12.             BaseDao.sqlMapper.startTransaction();   
  13.             System.out.println("事务开始");   
  14.             obj = mi.proceed();   
  15.             BaseDao.sqlMapper.commitTransaction();   
  16.             System.out.println("事务提交");   
  17.         } finally {   
  18.             BaseDao.sqlMapper.endTransaction();   
  19.             System.out.println("事务结束");   
  20.         }   
  21.         return obj;   
  22.     }   
  23.   
  24. }   

4. 最后把拦截器绑定到Guice全局的Injector当中。这里请注意静态引入import static。bindInterceptor方法的前两个参数一个是用来过滤类,一个用来过滤方法。好了,这样你所有GuiceRemoteServiceServlet类的子类的带有Transaction标注的方法都将被纳入事务管理了。

 

Java代码
  1. private static final Injector injector = Guice.createInjector(new Module() {   
  2.   
  3.     @Override  
  4.     public void configure(Binder binder) {   
  5.            
  6.         binder.bindInterceptor(   
  7.             subclassesOf(GuiceRemoteServiceServlet.class),    
  8.             any(),   
  9.             new ExceptionInterceptor()   
  10.         );   
  11.            
  12.         binder.bindInterceptor(   
  13.             subclassesOf(GuiceRemoteServiceServlet.class),    
  14.             annotatedWith(Transaction.class),   
  15.             new TransactionInterceptor()   
  16.         );   
  17.     }   
  18. });  

发表评论