package com.dmsd.util; import org.apache.ibatis.session.SqlSession; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * @introduce 处理事务动态代理工具类 * * @author xingMeiLing * @DATE 2020/6/19 **/ public class TransactionInvocationHandler implements InvocationHandler { /*声明需要实现代理的对象target*/ private Object target; public TransactionInvocationHandler(Object target){ this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args){ SqlSession sqlSession = null; Object object = null; try{ sqlSession = SqlSessionUtil.getSession(); // 处理业务逻辑 object = method.invoke(target,args); // 调用事物 sqlSession.commit(); } catch (Exception e){ // 出现问题,进行事物回滚 sqlSession.rollback(); }finally { // 最后一定要执行的,关闭session,线程池回收线程 SqlSessionUtil.myCloseSession(sqlSession); } return object; } /** * @ 获取代理类的对象 * @author xingMeiLing * @return 代理类对象 */ public Object getProxy(){ /*传入目标对象的加载器:target.getClass().getClassLoader() 该目标对象的接口类:target.getClass().getInterfaces() 调用当前对象:this(目的是调用invoke方法)*/ return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(), this); } }
来源:oschina
链接:https://my.oschina.net/u/4256940/blog/4319073