JDK動(dòng)態(tài)代理實(shí)現(xiàn)自己的事務(wù)管理器

spring aop介紹

spring提供了五種通知類型
  • Interception Around
    JointPoint前后調(diào)用,實(shí)現(xiàn)此類需要實(shí)現(xiàn)接口MethodInterceptor。
  • Before通知
    需要實(shí)現(xiàn)接口MethodBeforeAdvice圣蝎。
  • After Returning 通知
    需要實(shí)現(xiàn)接口AfterReturningAdvice测暗。
  • Throw通知
    需要實(shí)現(xiàn)接口ThrowsAdvice
  • Introduction通知
    需要實(shí)現(xiàn)接口IntroductionAdvisor和IntroductionInterceptor沽瞭。

怎樣實(shí)現(xiàn)自己的事務(wù)管理器

  • 定義業(yè)務(wù)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 + "]";
    }
    
}
  • 業(yè)務(wù)service接口實(shí)現(xiàn)
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) {
            //回滾相關(guān)事務(wù)  父類或子類實(shí)現(xiàn)
            doCloseTransactionAfterThrowing(geTransactionInfo(), e);
            throw e;
        } finally {
            //設(shè)置transaction 狀態(tài)
            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動(dòng)態(tài)代理InvocationHandler鹿榜,實(shí)現(xiàn)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();
    }*/
    
    /**
     * 創(chuàng)建代理
     * 
     * @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();
    }
    
}
  • 實(shí)現(xiàn)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 事務(wù)相關(guān)信息

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("開始執(zhí)行insert方法");
        System.out.println("方法返回值 : " + userService2.insert(new StudentDemo()));
        
        System.out.println("====================================");
        
        System.out.println("開始執(zhí)行insert2方法");
        System.out.println(userService2.insert2(new StudentDemo()));
    }
}
  • 運(yùn)行結(jié)果
begin transation
insert success!
docommit
方法返回值 : true
====================================
開始執(zhí)行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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市周荐,隨后出現(xiàn)的幾起案子狭莱,更是在濱河造成了極大的恐慌,老刑警劉巖概作,帶你破解...
    沈念sama閱讀 218,451評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)罕袋,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評論 3 394
  • 文/潘曉璐 我一進(jìn)店門榆纽,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了斧蜕?”我有些...
    開封第一講書人閱讀 164,782評論 0 354
  • 文/不壞的土叔 我叫張陵均芽,是天一觀的道長仲锄。 經(jīng)常有香客問我镣奋,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,709評論 1 294
  • 正文 為了忘掉前任陶贼,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,733評論 6 392
  • 文/花漫 我一把揭開白布晨横。 她就那樣靜靜地躺著滞时,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上渤滞,一...
    開封第一講書人閱讀 51,578評論 1 305
  • 那天肿孵,我揣著相機(jī)與錄音大莫,去河邊找鬼懈凹。 笑死们陆,一個(gè)胖子當(dāng)著我的面吹牛椅文,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播忙干,決...
    沈念sama閱讀 40,320評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起涂乌,我...
    開封第一講書人閱讀 39,241評論 0 276
  • 序言:老撾萬榮一對情侶失蹤丈莺,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后送丰,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體缔俄,經(jīng)...
    沈念sama閱讀 45,686評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,878評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了牵现。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片铐懊。...
    茶點(diǎn)故事閱讀 39,992評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖瞎疼,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情壁畸,我是刑警寧澤贼急,帶...
    沈念sama閱讀 35,715評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站捏萍,受9級特大地震影響太抓,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜令杈,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,336評論 3 330
  • 文/蒙蒙 一走敌、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧逗噩,春花似錦掉丽、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,912評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至纲刀,卻和暖如春项炼,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背示绊。 一陣腳步聲響...
    開封第一講書人閱讀 33,040評論 1 270
  • 我被黑心中介騙來泰國打工锭部, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人面褐。 一個(gè)月前我還...
    沈念sama閱讀 48,173評論 3 370
  • 正文 我出身青樓拌禾,卻偏偏與公主長得像,于是被迫代替她去往敵國和親盆耽。 傳聞我的和親對象是個(gè)殘疾皇子蹋砚,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,947評論 2 355

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn)摄杂,斷路器坝咐,智...
    卡卡羅2017閱讀 134,657評論 18 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,815評論 6 342
  • 0.前言 本文主要想闡述的問題如下:什么動(dòng)態(tài)代理(AOP)以及如何用JDK的Proxy和InvocationHan...
    SYFHEHE閱讀 2,269評論 1 7
  • 什么是Spring Spring是一個(gè)開源的Java EE開發(fā)框架。Spring框架的核心功能可以應(yīng)用在任何Jav...
    jemmm閱讀 16,464評論 1 133
  • 對大多數(shù)Java開發(fā)者來說析恢,Spring事務(wù)管理是Spring應(yīng)用中最常用的功能墨坚,使用也比較簡單。本文主要從三個(gè)方...
    sherlockyb閱讀 3,209評論 0 18