最近在学习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);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString(), e);
}
}
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
//第二步:
// If the proxy class defined by the given loader implementing
// the given interfaces exists, this will simply return the cached copy;
// otherwise, it will create the proxy class via the ProxyClassFactory
//注释很明白,就是先看缓存有没有,没有则创建代理类
return proxyClassCache.get(loader, interfaces);
}
//proxyClassCache 这个对象是什么?下面给proxyClassCache的赋值操作方法,
//final和static修饰的变量 ,所以在加载Proxy类的时候给proxyClassCache 赋值
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
//WeakCache类的构造方法
//keyFactory是用来生产key的,ProxyClassFactory是用来生产代理类对象的,它俩都是实现了
//BiFunction接口的Proxy的内部类
public WeakCache(BiFunction<K, P, ?> subKeyFactory,
BiFunction<K, P, V> valueFactory) {
this.subKeyFactory = Objects.requireNonNull(subKeyFactory);
this.valueFactory = Objects.requireNonNull(valueFactory);
}
//需要到WeakCache类中,找get方法
下面是WeakCache类的get方法
public V get(K key, P parameter) {
Objects.requireNonNull(parameter);
expungeStaleEntries();
//对 key进行处理,将 null转换为一个 Object对象
Object cacheKey = CacheKey.valueOf(key, refQueue);
// lazily install the 2nd level valuesMap for the particular cacheKey
//延迟初始化,二级MAP
ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
if (valuesMap == null) {
ConcurrentMap<Object, Supplier<V>> oldValuesMap
= map.putIfAbsent(cacheKey,
valuesMap = new ConcurrentHashMap<>());
if (oldValuesMap != null) {
valuesMap = oldValuesMap;
}
}
// create subKey and retrieve the possible Supplier<V> stored by that
// subKey from valuesMap
//subKey的生成,需要查看Proxy中的KeyFactory内部类的apply方法,代码在下面
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
//从我们的二级map中根据key,取出来的值可能是
//代理类的工厂Factory 或缓存CacheValue
Supplier<V> supplier = valuesMap.get(subKey);
Factory factory = null;
while (true) {
if (supplier != null) {//缓存中有supplier
// supplier might be a Factory or a CacheValue<V> instance
V value = supplier.get();
//这儿取值可能情况有俩种,如果是Factory,则是生成代理类,可能失败
//如果是CacheValue中,取值,可能为null
if (value != null) {//supplier的get返回值不为空
return value;
}
}
// else no supplier in cache
// or a supplier that returned null (could be a cleared CacheValue
// or a Factory that wasn't successful in installing the CacheValue)
// lazily construct a Factory
if (factory == null) {
factory = new Factory(key, parameter, subKey, valuesMap);
}
if (supplier == null) {
supplier = valuesMap.putIfAbsent(subKey, factory);
if (supplier == null) {
// successfully installed Factory
supplier = factory;
}
// else retry with winning supplier
} else {
if (valuesMap.replace(subKey, supplier, factory)) {
// successfully replaced
// cleared CacheEntry / unsuccessful Factory
// with our Factory
supplier = factory;
} else {
// retry with current supplier
supplier = valuesMap.get(subKey);
}
}
}
}
//下面的代码是CacheKey中的
private static final Object NULL_KEY = new Object();
//对key进行包装,为NULL则返回一个Object对象
static <K> Object valueOf(K key, ReferenceQueue<K> refQueue) {
return key == null
// null key means we can't weakly reference it,
// so we use a NULL_KEY singleton as cache key
? NULL_KEY
// non-null key requires wrapping with a WeakReference
: new CacheKey<>(key, refQueue);
}
//WeakCache类中的map的定义,是一个二级MAP结构,同时用的是并发容器MAP
//简单理解,外层Map的key就是类加载器运算后生成的,里层的二级map的key就是类加载器和接口数组经
//过运算生成的,subMap中的value就是我们的代理类的一个持有者,factory或者cacheValue
// the key type is Object for supporting null key
private final ConcurrentMap<Object, ConcurrentMap<Object, Supplier<V>>> map
= new ConcurrentHashMap<>();
//KeyFactory的定义,负责生成我们的subKey
private static final class KeyFactory
implements BiFunction<ClassLoader, Class<?>[], Object>
{
@Override
public Object apply(ClassLoader classLoader, Class<?>[] interfaces) {
switch (interfaces.length) {
case 1: return new Key1(interfaces[0]); // the most frequent
case 2: return new Key2(interfaces[0], interfaces[1]);
case 0: return key0;
default: return new KeyX(interfaces);
}
}
}
上面分析:
V value = supplier.get();
这一步,我们只分析如果这个supplier是一个Factory时,也就是第一次执行UserMapper userMapper = sqlSession.getMapper(UserMapper.class);时如何生成代理类的对象(不是代理类的实例,是代表这个代理类的对象,具体可以查看java反射中Class)。第1次之后再调用时,我们的代理类对象从缓存ValueCache中拿,然后代理类对象拿到构造器对象,然后创建一个代理类的实例出来。(这个实例是,每次调用生成一个新的)
更简单的理解:生成的代理类Class只生成一次,然后缓存起来,之后每次调用getMapper时,新生成这个代理类的实例对象。
//Factory中的get方法
@Override
public synchronized V get() { // serialize access
// re-check
Supplier<V> supplier = valuesMap.get(subKey);
if (supplier != this) {
// something changed while we were waiting:
// might be that we were replaced by a CacheValue
// or were removed because of failure ->
// return null to signal WeakCache.get() to retry
// the loop
//这一句判断很关键,比如我们的下单逻辑,只能执行一次,执行完之后状态修改,
//别的线程,拿到锁之后,先查看状态,是否符合预期,如果状态不符合,
//就不执行后续操作了。
//或者一些要求幂等性的方法
return null;
}
// else still us (supplier == this)
// create new value
V value = null;
try {//创建我们的代理类对象
value = Objects.requireNonNull(valueFactory.apply(key, parameter));
} finally {
if (value == null) { // remove us on failure
valuesMap.remove(subKey, this);
}
}
// the only path to reach here is with non-null value
assert value != null;
//下面的逻辑,就是将我们的代理类对象缓存起来,将之前的subMap中的value值由factory
//替换为我们的cacheValue ,
//之后我们的获取代理类对象操作就不需要重新生成了,可以直接从缓存CacheValue 中get()
// wrap value with CacheValue (WeakReference)
CacheValue<V> cacheValue = new CacheValue<>(value);
// try replacing us with CacheValue (this should always succeed)
if (valuesMap.replace(subKey, this, cacheValue)) {
// put also in reverseMap
reverseMap.put(cacheValue, Boolean.TRUE);
} else {
throw new AssertionError("Should not reach here");
}
// successfully replaced us with new CacheValue -> return the value
// wrapped by it
return value;
}
}
下面分析:factory生成代理类对象。前面说过这个factory是一个ProxyClassFactory类型。所以我们查看ProxyClassFactory里的apply方法。
value = Objects.requireNonNull(valueFactory.apply(key, parameter));
@Override
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
for (Class<?> intf : interfaces) {
/*
* Verify that the class loader resolves the name of this
* interface to the same Class object.
*/
Class<?> interfaceClass = null;
try {
interfaceClass = Class.forName(intf.getName(), false, loader);
} catch (ClassNotFoundException e) {
}
if (interfaceClass != intf) {
throw new IllegalArgumentException(
intf + " is not visible from class loader");
}
/*
* Verify that the Class object actually represents an
* interface.
*/
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* Verify that this interface is not a duplicate.
*/
if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
throw new IllegalArgumentException(
"repeated interface: " + interfaceClass.getName());
}
}
String proxyPkg = null; // package to define proxy class in
int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
/*
* Record the package of a non-public proxy interface so that the
* proxy class will be defined in the same package. Verify that
* all non-public proxy interfaces are in the same package.
*/
for (Class<?> intf : interfaces) {
int flags = intf.getModifiers();
if (!Modifier.isPublic(flags)) {
accessFlags = Modifier.FINAL;
String name = intf.getName();
int n = name.lastIndexOf('.');
String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
if (proxyPkg == null) {
proxyPkg = pkg;
} else if (!pkg.equals(proxyPkg)) {
throw new IllegalArgumentException(
"non-public interfaces from different packages");
}
}
}
if (proxyPkg == null) {
// if no non-public proxy interfaces, use com.sun.proxy package
proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
}
/*
* Choose a name for the proxy class to generate.
*/
long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* Generate the specified proxy class.
*关键代码,生成代理类的class文件,返回的是char数组
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {//返回代理类的对象
return defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);
} catch (ClassFormatError e) {
/*
* A ClassFormatError here means that (barring bugs in the
* proxy class generation code) there was some other
* invalid aspect of the arguments supplied to the proxy
* class creation (such as virtual machine limitations
* exceeded).
*/
throw new IllegalArgumentException(e.toString());
}
}
}
private static final boolean saveGeneratedFiles = (Boolean)AccessController.doPrivileged(new GetBooleanAction("sun.misc.ProxyGenerator.saveGeneratedFiles"));
public static byte[] generateProxyClass(final String var0, Class<?>[] var1, int var2) {
ProxyGenerator var3 = new ProxyGenerator(var0, var1, var2);
final byte[] var4 = var3.generateClassFile();
if (saveGeneratedFiles) {//这个标识就是,控制是否将代理类class文件保存到磁盘
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
try {
int var1 = var0.lastIndexOf(46);
Path var2;
if (var1 > 0) {
Path var3 = Paths.get(var0.substring(0, var1).replace('.', File.separatorChar));
Files.createDirectories(var3);
var2 = var3.resolve(var0.substring(var1 + 1, var0.length()) + ".class");
} else {
var2 = Paths.get(var0 + ".class");
}
Files.write(var2, var4, new OpenOption[0]);
return null;
} catch (IOException var4x) {
throw new InternalError("I/O exception saving generated file: " + var4x);
}
}
});
}
return var4;
}
看代码知道,有个开关可以控制生成的代理类Class文件保存到磁盘中。
上面是我保存到本地的代理类的Class文件,下面是代码(反编译后的)
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.sun.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
import learn.User;
import learn.UserMapper;
public final class $Proxy0 extends Proxy implements UserMapper {
private static Method m1;
private static Method m2;
private static Method m3;
private static Method m0;
public $Proxy0(InvocationHandler var1) throws {
super(var1);
}
public final boolean equals(Object var1) throws {
try {
return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final String toString() throws {
try {
return (String)super.h.invoke(this, m2, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final User selectUser(String var1) throws {
try {
return (User)super.h.invoke(this, m3, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final int hashCode() throws {
try {
return (Integer)super.h.invoke(this, m0, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
static {
try {
m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
m2 = Class.forName("java.lang.Object").getMethod("toString");
m3 = Class.forName("learn.UserMapper").getMethod("selectUser", Class.forName("java.lang.String"));
m0 = Class.forName("java.lang.Object").getMethod("hashCode");
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
}
总结:
1.我们多次调用
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
实际上使用的同一个代理类,只有第一次是通过factory生成的,之后是从缓存ValueCache中取值。
2.我们生成的代理类是继承了Proxy类的,所以JDK动态代理不支持继承方式,只支持接口方式。
3.我们的InvocationHandler接口的实现类的对象h,作为构造函数的入参,传给我们的代理类。
4.我们代理类的代理方法是委托给h的invoke方法的。