动态代理工厂
public class MapperProxyFactory<T> {private final Class<T> mapperInterface;public MapperProxyFactory(Class<T> mapperInterface) {this.mapperInterface = mapperInterface;}public T newInstance(Map<String,String>sqlSession){final MapperProxy<T> mapperProxy=new MapperProxy<>(sqlSession,mapperInterface);return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(),new Class[]{mapperInterface}, mapperProxy);}}
newProxyInstance,方法有三个参数:
loader: 用哪个类加载器去加载代理对象
interfaces:动态代理类需要实现的接口
h:动态代理方法在执行时,会调用h里面的invoke方法去执行
动态代理类
public class MapperProxy<T> implements InvocationHandler, Serializable {private Map<String, String> sqlSession;private final Class<T> mapperInterface;public MapperProxy(Map<String, String> sqlSession, Class<T> mapperInterface) {this.sqlSession = sqlSession;this.mapperInterface = mapperInterface;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {if (Object.class.equals(method.getDeclaringClass())) {return method.invoke(this, args);} else {return "你的被代理了!" + sqlSession.get(mapperInterface.getName() + "." + method.getName());}}}
invoke三个参数:
proxy:就是代理对象,newProxyInstance方法的返回对象
method:调用的方法
args: 方法中的参数
调用案列
创建 接口
public interface IUserDao {String queryUser(String uid);Integer detailUser(String uid);}
调用
public class MpTest {@Testpublic void test_MapperProxyFactory() {//创建代理MapperProxyFactory<IUserDao> factory = new MapperProxyFactory<>(IUserDao.class);Map<String, String> sqlSession = new HashMap<>();sqlSession.put("cn.wh.dao.IUserDao.queryUser", "模拟执行 Mapper.xml 中 SQL 语句的操作:查询用户姓名");sqlSession.put("cn.bugstack.mybatis.test.dao.IUserDao.queryUserName", "模拟执行 Mapper.xml 中 SQL 语句的操作:查询用户年龄");IUserDao userDao = factory.newInstance(sqlSession);//调用方法String res = userDao.queryUser("10001");System.out.println(res);}}
