?Mybatis為我們提供插件技術(shù),在我們sql執(zhí)行流程過程中創(chuàng)建SqlSession的四大對象進(jìn)行自定義代碼處理的分裝其馏,實(shí)現(xiàn)一些特殊的需求夭苗。
接口定義:
我們在mybatis中使用插件都要實(shí)現(xiàn)Interceptor接口:
public interface Interceptor {
//它將攔截對象的原有方法缀遍,因此他是插件的核心方法筷弦,可以通過invocation參數(shù)反射調(diào)用原來的方法
Object intercept(Invocation invocation) throws Throwable;
//target是被攔截的對象溅潜,作用是給攔截對象生成一個代理對象术唬,并返回代理對象;
Object plugin(Object target);
//在plugin中配置所需要的參數(shù)滚澜,方法在初始化的時候被調(diào)用一次粗仓。
void setProperties(Properties properties);
}
插件的初始化:
插件的初始化是在Mybatis初始化的時候完成的,代碼在XMLConfigBuilder中的pluginElement(XNode parent):
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
//執(zhí)行
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
reader.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
//執(zhí)行
public Configuration parse() {
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
//執(zhí)行
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
//執(zhí)行
private void parseConfiguration(XNode root) {
try {
//issue #117 read properties first
propertiesElement(root.evalNode("properties"));
Properties settings = settingsAsProperties(root.evalNode("settings"));
loadCustomVfs(settings);
typeAliasesElement(root.evalNode("typeAliases"));
//解析插件
pluginElement(root.evalNode("plugins"));
objectFactoryElement(root.evalNode("objectFactory"));
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
reflectorFactoryElement(root.evalNode("reflectorFactory"));
settingsElement(settings);
// read it after objectFactory and objectWrapperFactory issue #631
environmentsElement(root.evalNode("environments"));
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
typeHandlerElement(root.evalNode("typeHandlers"));
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
//插件的初始化
private void pluginElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
String interceptor = child.getStringAttribute("interceptor");
Properties properties = child.getChildrenAsProperties();
Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
interceptorInstance.setProperties(properties);
configuration.addInterceptor(interceptorInstance);
}
}
}
插件的使用:
從Sql執(zhí)行流程中我們很容易明白插件的調(diào)用位置和代碼:
executor = interceptorChain.pluginAll(executor);
public class InterceptorChain {
private final List<Interceptor> interceptors = new ArrayList<Interceptor>();
//調(diào)用plugs鏈
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
//可以根據(jù)Interceptor接口的定義返回的是代理對象
target = interceptor.plugin(target);
}
return target;
}
//添加plugs鏈
public void addInterceptor(Interceptor interceptor) {
interceptors.add(interceptor);
}
//獲取plugs鏈
public List<Interceptor> getInterceptors() {
return Collections.unmodifiableList(interceptors);
}
}
這里的重點(diǎn)還是interceptor.plugin(target)創(chuàng)建代理的過程设捐,這個創(chuàng)建代理的過程Mybatis給我們提供一個工具類org.apache.ibatis.plugin.Plugin可以為我們提供非常便利的創(chuàng)建代理對象:
public class Plugin implements InvocationHandler {
private Object target;
private Interceptor interceptor;
private Map<Class<?>, Set<Method>> signatureMap;
//構(gòu)造方法
private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
this.target = target;//目標(biāo)對象
this.interceptor = interceptor;//目標(biāo)對象實(shí)現(xiàn)的接口
this.signatureMap = signatureMap;//Signature的注解信息
}
//靜態(tài)方法獲取代理
public static Object wrap(Object target, Interceptor interceptor) {
//解析plug實(shí)現(xiàn)類中的注解配置
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
//獲取目標(biāo)對象的Class對象
Class<?> type = target.getClass();
//從signatureMap獲取匹配的interfaces對象
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
if (interfaces.length > 0) {
//創(chuàng)建代理
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
}
return target;
}
//InvocationHandler 額外功能方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
//signatureMap中獲取匹配的方法
Set<Method> methods = signatureMap.get(method.getDeclaringClass());
if (methods != null && methods.contains(method)) {
//調(diào)用插件interceptor中的攔截方法
return interceptor.intercept(new Invocation(target, method, args));
}
//直接待用目標(biāo)方法
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
//解析plug實(shí)現(xiàn)類中的注解配置
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
//獲取Interceptes注解
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
// plug實(shí)現(xiàn)類不存在Intercepts注解 則拋出異常
if (interceptsAnnotation == null) {
throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
//獲取配置的Singature數(shù)組
Signature[] sigs = interceptsAnnotation.value();
//容器用于保持目標(biāo)對象和注解匹配成功信息
//key :interceptor中要攔截的目標(biāo)類(sqlSession的四大對象)
//value:要攔截的方法
Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
//便利注解中配置的Signature數(shù)組
for (Signature sig : sigs) {
Set<Method> methods = signatureMap.get(sig.type());
if (methods == null) {
methods = new HashSet<Method>();
signatureMap.put(sig.type(), methods);
}
try {
Method method = sig.type().getMethod(sig.method(), sig.args());
methods.add(method);
} catch (NoSuchMethodException e) {
throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);
}
}
return signatureMap;
}
private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
Set<Class<?>> interfaces = new HashSet<Class<?>>();
while (type != null) {
for (Class<?> c : type.getInterfaces()) {
if (signatureMap.containsKey(c)) {
interfaces.add(c);
}
}
type = type.getSuperclass();
}
return interfaces.toArray(new Class<?>[interfaces.size()]);
}
}
插件工具類注解案例:
//Intercepts 注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Intercepts {
Signature[] value();
}
//Signature注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface Signature {
Class<?> type();
String method();
Class<?>[] args();
}
//案例
@Intercepts({
@Signature(type=Executor.class,
method= "query",
args = { MappedStatement.class, Object.class,RowBounds.class,
ResultHandler.class }),
@Signature(type = Executor.class,
method = "update",
args = { MappedStatement.class, Object.class }) })