ProxyFactory
是创建代理类的工厂接口,其中的setProperties
方法用来对工厂进行属性设置,但是mybatis内置的两个实现类都没有实现该接口,所以不支持属性设置。createProxy
方法用来创建一个代理对象
public interface ProxyFactory { // 设置工厂属性 default void setProperties(Properties properties) { } // 创建代理对象 Object createProxy(Object target, ResultLoaderMap lazyLoader, Configuration configuration, ObjectFactory objectFactory, List> constructorArgTypes, List
ProxyFactory
接口有2个实现类,CglibProxyFactory
和JavassistProxyFactor
类。这两个实现类整体结构高度一致,内部类、方法设置都一样,只是实现原理不同。CglibProxyFactory
基于cglib实现,JavassistProxyFactor
基于javassist实现。
接下来以CglibProxyFactory类为源码进行分析:
CglibProxyFactory
类中提供了两个创建代理对象的方法。其中createProxy
方法重写了一个普通的代理对象,createDeserializationProxy方法用来创建一个反序列化的代理对象。
public class CglibProxyFactory implements ProxyFactory { private static final String FINALIZE_METHOD = "finalize"; private static final String WRITE_REPLACE_METHOD = "writeReplace"; public CglibProxyFactory() { try { Resources.classForName("net.sf.cglib.proxy.Enhancer"); } catch (Throwable e) { throw new IllegalStateException("Cannot enable lazy loading because CGLIB is not available. Add CGLIB to your classpath.", e); } } // 创建一个代理 @Override public Object createProxy(Object target, ResultLoaderMap lazyLoader, Configuration configuration, ObjectFactory objectFactory, List> constructorArgTypes, List
代理类最核心的方法是intercept
方法,当被代理对象的其他方法被调用时,intercept方法的处理方式是:
如果设置了激进懒加载或者被调用的是触发全局加载的方法,则直接加载所有未加载的属性。
如果被调用的是属性写方法,则将该方法从懒加载列表中删除,因为此时数据库中的数据已经不是最新的,没有必要再去加载,然后进行属性的写入操作。
如果被调用的是读方法,则该属性尚未被懒加载的情况下,则加载该属性,如果该属性已经被懒加载过,则直接读取该属性。
ResultLoaderMap类:
被代理对象可能会有多个属性可以被懒加载,这些尚未完成加载的属性是在ResultLoaderMap
类的实例中存储的。ResultLoaderMap
类主要就是一个map类,该类key为属性名的大写,value
为LoadPair对象。LoadPair类是ResultLoaderMap类的内部类,它能实现对应属性的懒加载功能。
public static class LoadPair implements Serializable { private static final long serialVersionUID = 20130412; // 用来根据反射得到数据库连接的方法名 private static final String FACTORY_METHOD = "getConfiguration"; // 判断是否经过了序列化的标志位,因为该属性被设置了transient,经过一次序列化和反序列化后会变为null private final transient Object serializationCheck = new Object(); // 输出结果对象的封装 private transient MetaObject metaResultObject; // 用以加载未加载属性的加载器 private transient ResultLoader resultLoader; // 日志记录器 private transient Log log; // 用来获取数据库连接的工厂 private Class> configurationFactory; // 未加载的属性的属性名 private String property; // 能够加载未加载属性的SQL的编号 private String mappedStatement; // 能够加载未加载属性的SQL的参数 private Serializable mappedParameter; private LoadPair(final String property, MetaObject metaResultObject, ResultLoader resultLoader) { this.property = property; this.metaResultObject = metaResultObject; this.resultLoader = resultLoader; if (metaResultObject != null && metaResultObject.getOriginalObject() instanceof Serializable) { final Object mappedStatementParameter = resultLoader.parameterObject; if (mappedStatementParameter instanceof Serializable) { this.mappedStatement = resultLoader.mappedStatement.getId(); this.mappedParameter = (Serializable) mappedStatementParameter; this.configurationFactory = resultLoader.configuration.getConfigurationFactory(); } else { Log log = this.getLogger(); if (log.isDebugEnabled()) { log.debug("Property [" + this.property + "] of [" + metaResultObject.getOriginalObject().getClass() + "] cannot be loaded " + "after deserialization. Make sure it's loaded before serializing " + "forenamed object."); } } } } public void load() throws SQLException { if (this.metaResultObject == null) { throw new IllegalArgumentException("metaResultObject is null"); } if (this.resultLoader == null) { throw new IllegalArgumentException("resultLoader is null"); } this.load(null); } /** * 进行加载操作 * @param userObject 需要被懒加载的对象(只有当this.metaResultObject == null || this.resultLoader == null才生效,否则会采用属性metaResultObject对应的对象) * @throws SQLException */ public void load(final Object userObject) throws SQLException { if (this.metaResultObject == null || this.resultLoader == null) { // 输出结果对象的封装不存在或者输出结果加载器不存在 // 判断用以加载属性的对应的SQL语句存在 if (this.mappedParameter == null) { throw new ExecutorException("Property [" + this.property + "] cannot be loaded because " + "required parameter of mapped statement [" + this.mappedStatement + "] is not serializable."); } final Configuration config = this.getConfiguration(); // 取出用来加载结果的SQL语句 final MappedStatement ms = config.getMappedStatement(this.mappedStatement); if (ms == null) { throw new ExecutorException("Cannot lazy load property [" + this.property + "] of deserialized object [" + userObject.getClass() + "] because configuration does not contain statement [" + this.mappedStatement + "]"); } // 创建结果对象的包装 this.metaResultObject = config.newMetaObject(userObject); // 创建结果加载器 this.resultLoader = new ResultLoader(config, new ClosedExecutor(), ms, this.mappedParameter, metaResultObject.getSetterType(this.property), null, null); } // 只要经历过持久化,则可能在别的线程中了。为这次惰性加载创建的新线程ResultLoader if (this.serializationCheck == null) { // 取出原来的ResultLoader中的必要信息,然后创建一个新的 // 这是因为load函数可能在不同的时间多次执行(第一次加载属性A,又过了好久加载属性B)。 // 而该对象的各种属性是跟随对象的,加载属性B时还保留着加载属性A时的状态,即ResultLoader是加载属性A时设置的 // 则此时ResultLoader中的Executor在ResultLoader中被替换成了一个能运行的Executor,而不是ClosedExecutor // 能运行的Executor的状态可能不是close,这将导致它被复用,从而引发多线程问题 // 是不是被两次执行的一个关键点就是有没有经过序列化,因为执行完后会被序列化并持久化 final ResultLoader old = this.resultLoader; this.resultLoader = new ResultLoader(old.configuration, new ClosedExecutor(), old.mappedStatement, old.parameterObject, old.targetType, old.cacheKey, old.boundSql); } this.metaResultObject.setValue(property, this.resultLoader.loadResult()); } private Configuration getConfiguration() { if (this.configurationFactory == null) { throw new ExecutorException("Cannot get Configuration as configuration factory was not set."); } Object configurationObject; try { final Method factoryMethod = this.configurationFactory.getDeclaredMethod(FACTORY_METHOD); if (!Modifier.isStatic(factoryMethod.getModifiers())) { throw new ExecutorException("Cannot get Configuration as factory method [" + this.configurationFactory + "]#[" + FACTORY_METHOD + "] is not static."); } if (!factoryMethod.isAccessible()) { configurationObject = AccessController.doPrivileged((PrivilegedExceptionAction) () -> { try { factoryMethod.setAccessible(true); return factoryMethod.invoke(null); } finally { factoryMethod.setAccessible(false); } }); } else { configurationObject = factoryMethod.invoke(null); } } catch (final ExecutorException ex) { throw ex; } catch (final NoSuchMethodException ex) { throw new ExecutorException("Cannot get Configuration as factory class [" + this.configurationFactory + "] is missing factory method of name [" + FACTORY_METHOD + "].", ex); } catch (final PrivilegedActionException ex) { throw new ExecutorException("Cannot get Configuration as factory method [" + this.configurationFactory + "]#[" + FACTORY_METHOD + "] threw an exception.", ex.getCause()); } catch (final Exception ex) { throw new ExecutorException("Cannot get Configuration as factory method [" + this.configurationFactory + "]#[" + FACTORY_METHOD + "] threw an exception.", ex); } if (!(configurationObject instanceof Configuration)) { throw new ExecutorException("Cannot get Configuration as factory method [" + this.configurationFactory + "]#[" + FACTORY_METHOD + "] didn't return [" + Configuration.class + "] but [" + (configurationObject == null ? "null" : configurationObject.getClass()) + "]."); } return Configuration.class.cast(configurationObject); } private Log getLogger() { if (this.log == null) { this.log = LogFactory.getLog(this.getClass()); } return this.log; } }
到此这篇关于mybatis
源码解读之executor
包懒加载功能 的文章就介绍到这了,更多相关executor包懒加载功能 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!