AOP思想控制事务

1.自已实现编程式事务(可以自定义将某些方法放入事务中)
public class BeanFactory {
    private static Set includeMethod = new HashSet();//需要控制事务的方法
    
    static{
        includeMethod.add("transfer");
    }
    
    public static BusinessService getBusinessSerivce(){
        final BusinessService s = new BusinessServiceImpl();
        BusinessService proxyS = (BusinessService)Proxy.newProxyInstance(s.getClass().getClassLoader(), 
                s.getClass().getInterfaces(), 
                new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args)
                            throws Throwable {
                        
                        String methodName = method.getName();
                        if(includeMethod.contains(methodName)){
                        
                            Object rtValue = null;
                            try{
                                TransactionManager.startTransaction();
                                rtValue = method.invoke(s, args);
                                TransactionManager.commit();
                            }catch(Exception e){
                                TransactionManager.rollback();
                                e.printStackTrace();
                            }finally{
                                TransactionManager.release();
                            }
                            return rtValue;
                        }else{
                            return method.invoke(s, args);
                        }
                    }
                });
        return proxyS;
    }
}

你可能感兴趣的:(AOP思想控制事务)