最近在学习MyBatis源码时,想要查看下JDK是如何自动生成的Mapper代理类。于是仔细看了源码,在这里做个记录。
package com.br.itwzhangzx02.learn;
import learn.User;
import learn.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
public class GeneratorClassFileTest {
public static void main(String[] args) {
//将生成的代理类class文件保存在磁盘
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
String resource = "resources/mybatis-config.xml";
SqlSessionFactory sqlSessionFactory;
try (InputStream inputStream = Resources.getResourceAsStream(resource)) {
//1、创建SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2、获取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = getUser(sqlSession);
System.out.println(user);
}catch (Exception e){
}
}
private static User getUser(SqlSession sqlSession) {
//3、获取mapper,断点在这儿,然后进入
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.toString();
//4、执行数据库操作,并处理结果集
return userMapper.selectUser("10");
}
}
//MapperProxyFactory 类中的方法 第三个入参mapperProxy就是实现了InvocationHandler接口的类的对象
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
//这个是MapperRegistry类中的方法,将mapperProxyFactory 在初始化解析xml时缓存到内存中。
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {//这儿,用对应的工厂负责new一个代理类的对象
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
然后直接查看我们JDK的Proxy.newProxyInstance方法
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
Objects.requireNonNull(h);
final Class<?>[] intfs = interfaces.clone();
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
/* 第一步:
* Look up or generate the designated proxy class.
* 这里使用到缓存技术,从缓存中取代理类,或者直接生成一个代理类
*/
Class<?> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
cons.setAccessible(true);
return null;
}
});
}
//通过反射机制,拿到代理类的构造器对象,然后构造器对象创建代理类的实例
return cons.newInstance(new Object[]{h});
} catch (IllegalAccessException|InstantiationException e) {
throw new InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString(), t);