JDK动态代理实现自己的事务管理器

spring aop介绍

spring提供了五种通知类型
  • Interception Around
    JointPoint前后调用,实现此类需要实现接口MethodInterceptor。
  • Before通知
    需要实现接口MethodBeforeAdvice。
  • After Returning 通知
    需要实现接口AfterReturningAdvice。
  • Throw通知
    需要实现接口ThrowsAdvice
  • Introduction通知
    需要实现接口IntroductionAdvisor和IntroductionInterceptor。

怎样实现自己的事务管理器

  • 定义业务service接口
package com.july.testspring.transaction;

public interface StudentService {
    public boolean insert(StudentDemo demo);

    public boolean insert2(StudentDemo studentDemo);
}
  • 定义DO类
package com.july.testspring.transaction;

import java.io.Serializable;

public class StudentDemo implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private int id;
    
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "StudentDemo [id=" + id + ", name=" + name + "]";
    }
    
}
  • 业务service接口实现
package com.july.testspring.transaction;

public class StudentServiceImpl implements StudentService {

    @Override
    public boolean insert(StudentDemo demo) {
        System.out.println("insert success!");
        return true;
    }

    @Override
    public boolean insert2(StudentDemo studentDemo) {
        System.out.println(1/0);
        return false;
    }
}

  • 定义Advice通知类
package com.july.testspring.transaction;

import java.lang.reflect.Method;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.util.StringUtils;

public class MyTransactionInterceptor implements MethodInterceptor {
    
    final ThreadLocal<TransactionInfo> transactionThread = new ThreadLocal<TransactionInfo>();

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        
        
        Class targetClass = (methodInvocation.getThis() != null) ? methodInvocation.getThis().getClass() : null;
        //
        if(methodInvocation.getMethod().getName().equals("toString")) {
            return "";
        }
        
        //begin Transaction
        TransactionInfo txInfo = createTransactionIfNecessary(methodInvocation.getMethod(), methodInvocation);
        Object retVal = null;
        try {
            retVal = methodInvocation.proceed();
        }catch (Throwable e) {
            //回滚相关事务  父类或子类实现
            doCloseTransactionAfterThrowing(geTransactionInfo(), e);
            throw e;
        } finally {
            //设置transaction 状态
            TransactionInfo info = geTransactionInfo();
            info.setSuccessStatus(StatusType.SUCCESS);
            doFinally(info);
        }
        //commit
        doCommitTransactionAfterReturning(geTransactionInfo());
        return retVal;
    }
    
    
    private void doFinally(TransactionInfo transactionInfo) {
        setTransactionInfo(transactionInfo);
    }

    private void doCommitTransactionAfterReturning(com.july.testspring.transaction.TransactionInfo geTransactionInfo) {
        System.out.println("docommit");
    }

    private void doCloseTransactionAfterThrowing(com.july.testspring.transaction.TransactionInfo geTransactionInfo,
            Throwable e) {
        System.out.println("rollback transaction");
        
    }

    private com.july.testspring.transaction.TransactionInfo createTransactionIfNecessary(Method method,
            MethodInvocation methodInvocation) {
        System.out.println("begin transation");
        TransactionInfo transactionInfo = new TransactionInfo();
        setTransactionInfo(transactionInfo);
        return transactionInfo;
    }

    public TransactionInfo geTransactionInfo() {
        return transactionThread.get();
    }
    
    public void setTransactionInfo(TransactionInfo transactionInfo) {
        transactionThread.set(transactionInfo);
    }
}
  • JDK动态代理InvocationHandler,实现InvocationHandler接口。

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.Advisor;
import org.springframework.aop.framework.Advised;

public class ProxyFactory implements InvocationHandler {
    
    public Object target;
    
    Advice advisor = (Advice) new MyTransactionInterceptor();
    
    public ProxyFactory(Object target) {
        this.target = target;
    }
    
    
    
    /*private static class ProxyFactoryClient {
        private static final ProxyFactory PROXY_FACTORY = new ProxyFactory();
    }*/
    
    /**
     * 创建代理
     * 
     * @param classzz
     * @return
     */
    public <T> T createProxy(Class<?> target) {
        return (T) Proxy.newProxyInstance(getClassLoader(),getMethodInterceptor(target), this);
    }

    private Class[] getMethodInterceptor(Class<?> target) {
        return target.getInterfaces();
    }



    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MethodInvocation methodInvocation = new TransactionMethodInvocation(args, target, method, this.advisor);
        return methodInvocation.proceed();
    }
    
    
    
    private ClassLoader getClassLoader() {
        return Thread.currentThread().getContextClassLoader();
    }
    
}
  • 实现MethodInvocation接口 TransactionMethodInvocation
package com.july.testspring.transaction;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import java.util.List;

import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.Advisor;

public class TransactionMethodInvocation implements MethodInvocation{
    
    protected Object[] arguments;
    
    protected final Object target;

    protected final Method method;
    
    Advice interceptorsAndDynamicMethodMatchers;
    
    private int currentInterceptorIndex = -1;

    public TransactionMethodInvocation(Object[] arguments,Object target,Method method,Advice interceptorsAndDynamicMethodMatchers) {
        this.arguments = arguments;
        this.target = target;
        this.method = method;
        this.interceptorsAndDynamicMethodMatchers = interceptorsAndDynamicMethodMatchers;
    }
    
    @Override
    public Object[] getArguments() {
        return this.arguments;
    }

    @Override
    public AccessibleObject getStaticPart() {
        return this.method;
    }

    @Override
    public Object getThis() {
        return this.target;
    }

    @Override
    public Object proceed() throws Throwable {
        if(++currentInterceptorIndex == 1) {
             return this.method.invoke(this.target, this.arguments);
        }
        return ((MethodInterceptor) interceptorsAndDynamicMethodMatchers).invoke(this);
    }

    @Override
    public Method getMethod() {
        return this.method;
    }

}

  • 定义TransactionInfo 事务相关信息

import java.util.concurrent.atomic.AtomicLong;

public class TransactionInfo {
    //1 成功  0 失败
    private volatile int status = 0;
    
    private final AtomicLong atomicLong = new AtomicLong();
    
    public void setSuccessStatus(StatusType type) {
        if(type.getCode() != status) {
            atomicLong.compareAndSet(0, type.getCode());
        }
    }
    
    public void setFailStatus(StatusType type) {
        if(type.getCode() != status) {
            atomicLong.compareAndSet(1, type.getCode());
        }
    }
}

  • 测试类

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.july.testspring.service.UserService;
import com.july.testspring.service.impl.UserServiceImpl;

public class Test {
    
    public static void main(String[] args) {
        StudentService userService2 = new ProxyFactory(new StudentServiceImpl()).createProxy(StudentServiceImpl.class);
        System.out.println("开始执行insert方法");
        System.out.println("方法返回值 : " + userService2.insert(new StudentDemo()));
        
        System.out.println("====================================");
        
        System.out.println("开始执行insert2方法");
        System.out.println(userService2.insert2(new StudentDemo()));
    }
}
  • 运行结果
begin transation
insert success!
docommit
方法返回值 : true
====================================
开始执行insert2方法
begin transation
rollback transaction
Exception in thread "main" java.lang.reflect.UndeclaredThrowableException
    at com.sun.proxy.$Proxy0.insert2(Unknown Source)
    at com.july.testspring.transaction.Test.main(Test.java:26)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.july.testspring.transaction.TransactionMethodInvocation.proceed(TransactionMethodInvocation.java:49)
    at com.july.testspring.transaction.MyTransactionInterceptor.invoke(MyTransactionInterceptor.java:26)
    at com.july.testspring.transaction.TransactionMethodInvocation.proceed(TransactionMethodInvocation.java:51)
    at com.july.testspring.transaction.ProxyFactory.invoke(ProxyFactory.java:51)
    ... 2 more
Caused by: java.lang.ArithmeticException: / by zero
    at com.july.testspring.transaction.StudentServiceImpl.insert2(StudentServiceImpl.java:13)
    ... 10 more
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,219评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,363评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,933评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,020评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,400评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,640评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,896评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,597评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,327评论 1 244
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,581评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,072评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,399评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,054评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,849评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,672评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,585评论 2 270

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,363评论 6 343
  • 0.前言 本文主要想阐述的问题如下:什么动态代理(AOP)以及如何用JDK的Proxy和InvocationHan...
    SYFHEHE阅读 2,205评论 1 7
  • 什么是Spring Spring是一个开源的Java EE开发框架。Spring框架的核心功能可以应用在任何Jav...
    jemmm阅读 16,360评论 1 133
  • 对大多数Java开发者来说,Spring事务管理是Spring应用中最常用的功能,使用也比较简单。本文主要从三个方...
    sherlockyb阅读 3,118评论 0 18