随手笔记之Mapper接口实例化
背景
已获取到对应Mapper的类,需要实例化Mapper,已调用其中的方法。
一、使用步骤
1.创建InterfaceInstanceUtil工具类
代码如下(示例):
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* 接口实例化工具类
*
* @author woodFang
* @date : 2024-4-23
*/
@Slf4j
public class InterfaceInstanceUtil implements InvocationHandler {
private Object target;
private static SqlSession sqlSession;
public InterfaceInstanceUtil() {
}
public InterfaceInstanceUtil(Object target) {
this.target = target;
}
public static Object newInstance(Class<?> converter) {
return Proxy.newProxyInstance(
converter.getClassLoader(),
new Class[]{converter},
new InterfaceInstanceUtil(sqlSession.getMapper(converter)));
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
return method.invoke(target, args);
}
public static void init(SqlSession sqlSession) {
InterfaceInstanceUtil.sqlSession = sqlSession;
log.info("[init][初始化 InterfaceInstanceUtil 成功]");
}
}
2.初始化InterfaceInstanceUtil
代码如下(示例):
@Bean
@SuppressWarnings("InstantiationOfUtilityClass")
public InterfaceInstanceUtil interfaceInstanceUtil(SqlSession sqlSession) {
InterfaceInstanceUtil.init(sqlSession);
return new InterfaceInstanceUtil();
}
3.使用示例
代码如下(示例):
//构造对象
BaseMapperX<?> baseMapperX = (BaseMapperX<?>) InterfaceInstanceUtil.newInstance(converter);
baseMapperX.getMapByFields(javaField, excelField);
其中converter为我获取到的BaseMapperX<?>类,通过InterfaceInstanceUtil.newInstance()方法构造对象,并成功调用baseMapperX 的getMapByFields方法