MyBatis之配置文件解析_插件plugins的作用及处理
简介
mybatis的插件即是拦截器,通过定义拦截器可以增强mybatis功能,如我们常用的mybatis分页插件可帮助我们实现分页功能。
拦截器接口及相关类
mybatis定义了拦截器接口Interceptor,当我们要实现一个拦截器时,要写一个类实现这个接口,主要要实现方法intercept()。
// mybatis定义的拦截接口,mybatis运行时,会调用intercept方法
public interface Interceptor {
//
Object intercept(Invocation invocation) throws Throwable;
// 默认实现,返回基于目标对象target及当前拦截器的动态代理对象
default Object plugin(Object target) {
return Plugin.wrap(target, this);
}
default void setProperties(Properties properties) {
// NOP
}
}
Invocation是mybatis提供的一个类, 封装了目标对象,方法,及方法参数。
// Invocation是mybatis提供了一个类
// 封装了目标对象,方法,及方法参数
public class Invocation {
private final Object target;
private final Method method;
private final Object[] args;
// 封装了方法的反射调用
public Object proceed() throws InvocationTargetException, IllegalAccessException {
return method.invoke(target, args);
}
}
PluginIn实现了JavaSE动态代理的InvocationHandler接口,在它的方法invoke()中调用了拦截器中的方法intercept()。
同时它还提供了两个重要的静态方法:
wrap()方法则返回基于目标对象target及当前拦截器的动态代理对象。
getSignatureMap()方法则用来处理拦截器类上的注解Intercepts,将解析到的要拦截的类型及方法存在signatureMap中
// 提供了Plugin类,实现了InvocationHandler接口
public class Plugin implements InvocationHandler {
private final Object target;
private final Interceptor interceptor;
// 插件要拦截的类型(用Class对象表示),此为键,及方法集合,此为值
private final Map<Class<?>, Set<Method>> signatureMap;
// 获得给定拦截器所要拦截的类及对应方法的集合,这是静态方法
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
// 获得这个拦截器上的注解Intercepts
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
// issue #251,若没有Intercepts注解,则抛出异常
// @Intercepts({
//type表示需要拦截的类型,method+args表示需要拦截的具体方法
// @Signature(type= Executor.class,method="query",
// args={MappedStatement.class, Object.class, RowBounds.class,
// ResultHandler.class})})
if (interceptsAnnotation == null) {
throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
// 获得注解上value属性的值,这是Signature数组
Signature[] sigs = interceptsAnnotation.value();
// 键是Class对象,值是要拦截的方法的集合,这些数据都从注解中获取
Map<Class<?>, Set<Method>> signatureMap = new HashMap<>();
for (Signature sig : sigs) {
Set<Method> methods = signatureMap.computeIfAbsent(sig.type(), k -> new HashSet<>());
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;
}
// 包装一个拦截器为动态代理代理对象
public static Object wrap(Object target, Interceptor interceptor) {
// 获得拦截器拦截的对象及其方法
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
Class<?> type = target.getClass();
// 获得要拦截的所有接口
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
if (interfaces.length > 0) {
// 创建动态代理对象,并返回
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 {
// 这个类型要拦截的所有方法
Set<Method> methods = signatureMap.get(method.getDeclaringClass());
if (methods != null && methods.contains(method)) {
// 调用拦截器中的拦截方法,这是客户拦截器中要实现的方法
return interceptor.intercept(new Invocation(target, method, args));
}
// 否则不做处理,调用原方法
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
}
拦截器类的实现
自定义拦截器类要实现mybatis定义的接口Interceptor,同时要用注解Intercepts示例定义要拦截的类型及方法,如下所示
// 拦截器必须定义@Intercepts注解,定义要拦截哪些类中的哪些方法
@Intercepts({
@Signature(type= Executor.class,method = "update",args = {MappedStatement.class,Object.class}),
@Signature(type= MyTest.class, method = "show",args={})
})
public class MyPlugin implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
System.out.println("=============================");
// 执行原方法
return invocation.proceed();
}
// 接收配置文件中配置的属性值
@Override
public void setProperties(Properties properties) {
System.out.println(properties);
}
}
拦截器的配置
在mybatis配置文件中可配置一个或多个插件,示例如下:
<plugins>
<!-- 可自定义一个或多个拦截器 -->
<!-- MyPlugin是一个实现了Interceptor接口的类 -->
<plugin interceptor="com.beck.mybatis.plugin.MyPlugin">
<!-- 拦截器可接收到这里配置的属性 -->
<property name="limitNum" value="10"/>
</plugin>
</plugins>
plugin子标签的属性interceptor定义了一个拦截器的类型,必须实现拦截器接口Interceptor, 其中子标签property可以Properties对象的形式传给拦截器。
拦截器配置的解析
拦截器配置的解析比较简单,即是解析plugins下的每个子标签plugin,获得属性interceptor的值,以此获得一个Interceptor对象,获得plugin子标签下的所有子标签property的name-value值,以Properties对象的形式传给Interceptor对象,调用Configuration对象的addInterceptor方法保存这个拦截器对象。
参见XMLConfigBuilder的方法private void pluginElement(XNode parent)
// 解析节点plugins
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).getDeclaredConstructor().newInstance();
interceptorInstance.setProperties(properties);
// 将拦截器对象保存到Configuration对象中
configuration.addInterceptor(interceptorInstance);
}
}
}
配置对象中拦截器的处理
Configuration对象持有一个InterceptorChain对象,并提供一个方法addInterceptor将一个组装好的拦截器对象加到InterceptorChain对象中。
InterceptorChain用来管理拦截器,持有一个拦截器对象的集合。
public class InterceptorChain {
// 拦截器对象集合,Configuration对象保存一个已解析好的拦截器对象时,即将这个对象加到这个集合中
private final List<Interceptor> interceptors = new ArrayList<>();
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
target = interceptor.plugin(target);
}
return target;
}
public void addInterceptor(Interceptor interceptor) {
interceptors.add(interceptor);
}
public List<Interceptor> getInterceptors() {
return Collections.unmodifiableList(interceptors);
}
}
Configuration在newExecutor(),newParameterHandler(),newResultSetHandler(),newStatementHandler()方法中将相应的已创建好的目标对象交给所有的已注册的拦截器,让拦截器拦截这些目标对象,默认情形下会为这些目标对象生成一个动态代理对象。下面是其中一个示例:
public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
ResultHandler resultHandler, BoundSql boundSql) {
ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
// resultSetHandler是目标对象,让所有已注册的拦截器都拦截这个目标对象
resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
return resultSetHandler;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构