Mapper代理对象创建时序图分析
Mapper代理对象创建分析
手动创建代理对象具体代码:
interface SearchDao{
List<Object> selectListObject(String msg);
}
interface SqlSession{
List<Object> selectList(String statement);
}
class DefaultSqlSession implements SqlSession{
@Override
public List<Object> selectList(String statement) {
System.out.println("select list");
return null;
}
}
class MapperProxyHandler implements InvocationHandler{
private Class<?> targetInterface;
private SqlSession sqlSession;
public MapperProxyHandler(Class<?> targetInterface,SqlSession sqlSession) {
this.targetInterface=targetInterface;
this.sqlSession=sqlSession;
}
/**
* invoke方法是为代理对象执行具体业务的方法
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("MapperProxyHandler.invoke()");
String className=targetInterface.getName();
String methodName=method.getName();
String statement=className+"."+methodName;
return sqlSession.selectList(statement);
}
}
class MapperProxyFactory{
//借助此属性封装要产生dialing对象的目标接口
private Class<?> targetInterface;
public MapperProxyFactory(Class<?> targetInterface){
this.targetInterface=targetInterface;
}
/**
*创建代理对象,并且为代理对象传入一个InvocationHandler
*在MyBatis中实现InvocationHandler的是MapperProxy
*在这里我定义的类是MapperProxyHandler
*/
public Object newInstance(MapperProxyHandler handler){
return Proxy.newProxyInstance(
targetInterface.getClassLoader(),
new Class[]{targetInterface},
handler);
}
}
测试代码
public static void main(String[] args) {
//获取目标接口的类对象
Class<?> targetInterface=SearchDao.class;
//获取SqlSession对象
SqlSession sqlSession =new DefaultSqlSession();
//创建一个MapperProxyHandler对象
MapperProxyHandler proxyHandler=new MapperProxyHandler(targetInterface,sqlSession);
//创建一个MapperProxyFactory 工厂对象
MapperProxyFactory proxyFactory=new MapperProxyFactory(targetInterface);
//基于工厂对象为目标接口创建代理对象
SearchDao searchDao=(SearchDao) proxyFactory.newInstance(proxyHandler);
System.out.println(searchDao.getClass().getName());
//基于代理对象执行业务操作
searchDao.selectListObject("hello mybatis");
}
测试结果