时间:2021-07-01 10:21:17 帮助过:18人阅读
2.动态代理实现类
package mybatis.dao.proxy; import mybatis.tools.MyBatisUtil; import org.apache.ibatis.session.SqlSession; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; /** * 描述: * 动态代理实现类 * * @author lance * @create 2018-10-15 9:33 */ public class MethodProxy implements InvocationHandler{ private Class<?> infClass; public MethodProxy(Class<?> infClass){ this.infClass = infClass; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { SqlSession session = MyBatisUtil.getSqlSession(); try{ Object mapper = session.getMapper(infClass); Object returnValue = method.invoke(mapper,args); session.commit(); return returnValue; }catch (Exception e){ session.rollback(); throw new RuntimeException(e.getMessage()); }finally { session.close(); } } }
3.代理工厂
package mybatis.dao.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; /** * 描述: * 代理对象工厂 * @author lance * @create 2018-10-15 11:42 */ public class MethodProxyFactory { public static <T> T createProxy(Class<T> infClass){ //调用回调处理器 InvocationHandler handler = new MethodProxy(infClass); return (T)Proxy.newProxyInstance(infClass.getClassLoader(),new Class[]{infClass},handler); } }
4.测试
import mybatis.dao.UserDaoInf; import mybatis.dao.proxy.MethodProxyFactory; import mybatis.entity.Users; import org.junit.Test; import java.util.List; /** * 描述: * * @author lance * @create 2018-09-10 15:15 */ public class UserDaoImplTest { @Test public void testFindUserById2(){ //动态生成代理对象 UserDaoInf dao = MethodProxyFactory.createProxy(UserDaoInf.class); Users user = dao.findUsersById("1001"); System.out.println(user.getUid()); System.out.println(user.getUserName()); List<Users> list = dao.findAll(); for (Users users : list) { System.out.println(users.getUid()); } } }
5.效果图
动态实现类(对数据库的增删改查)
标签:loader imp factor 动态 voc ssi getc ima except