Mybatis Mapper接口动态代理实现原理及二次开发

背景介绍

研究一个开源项目,做二次开发,与公司业务系统集成,基础数据打通,基础功能要做替换改造。研究代码发现,dao层操作就是一系列Mapper接口声明及MapperProvider的定义文件,以下是改造过程介绍:

关键配置

配置Sqlsession,mapper目录

DataSource dataSource = getDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();

Environment environment = new Environment(Constants.DEVELOPMENT, transactionFactory, dataSource);

Configuration configuration = new Configuration(environment);
configuration.setLazyLoadingEnabled(true);
//mappers包目录,据此扫描注解,动态代理生成相关mapper实现。
configuration.addMappers(ProjectMapper.class.getPackage().getName());

SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
sqlSessionFactory = builder.build(configuration);

获取mapper实现类

public static <T> T getMapper(Class<T> type){
	return getSqlSession().getMapper(type);
}

主要实现类

  • sqlSesstionTemplate
	public <T> T getMapper(Class<T> type) {
        return this.getConfiguration().getMapper(type, this);
    }
  • Configuration
	public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        return this.mapperRegistry.getMapper(type, sqlSession);
    }
  • MapperRegistry

    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory)this.knownMappers.get(type);
        if (mapperProxyFactory == null) {
            throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
        } else {
            try {
                return mapperProxyFactory.newInstance(sqlSession);
            } catch (Exception var5) {
                throw new BindingException("Error getting mapper instance. Cause: " + var5, var5);
            }
        }
    }
  • MapperProxyFactory
    见到久违的Proxy.newProxyInstance,InvocationHandler是MapperProxy。

    protected T newInstance(MapperProxy<T> mapperProxy) {
        return Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);
    }

    public T newInstance(SqlSession sqlSession) {
        MapperProxy<T> mapperProxy = new MapperProxy(sqlSession, this.mapperInterface, this.methodCache);
        return this.newInstance(mapperProxy);
    }
  • MapperProxy
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            if (Object.class.equals(method.getDeclaringClass())) {
                return method.invoke(this, args);
            }

            if (this.isDefaultMethod(method)) {
                return this.invokeDefaultMethod(proxy, method, args);
            }
        } catch (Throwable var5) {
            throw ExceptionUtil.unwrapThrowable(var5);
        }

        MapperMethod mapperMethod = this.cachedMapperMethod(method);
        return mapperMethod.execute(this.sqlSession, args);
    }
  • MapperMethod
    最终的实现是在execute方法里 执行的curd操作。

改造需求

mapper的实现基于动态代理,隐藏的很深,业务代码只有一个Mapper接口声明。
若要重新实现这个Mapper,又要尽可能减少相关代码的改造。
怎么实现呢?
总的原则:
1、不改动接口声明,只在需要改动的Mapper上添加Annotation.
2、获取mapper实现时,根据Annotation判断拦截,做自定义处理。
3、设置自定义Mapper实现为默认实现。

实现方式

  • Annotation声明
/**
 * 是否自定义实现mapper的标记,
 * 替换默认的jdk动态代理:基于sqlSession
 *
 *@author WongBin
 *@date 2019/10/11
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MapperAnnotation {
	/***
	 * mapper实现类的名称
	 */
	String value() default "";

	Class impl();
}
  • 自定义实现
@Component
@Primary
public class DatasourceMapperImpl implements DataSourceMapper {
	private static Logger logger = LoggerFactory.getLogger(DatasourceMapperImpl.class);

	@Override
	public int insert(DataSource dataSource) {
		logger.info("custom-insert:{}",dataSource);
		dataSource.setId(1);
		return 1;
	}
	....
}
  • 改造mapper获取
public static <T> T getMapper(Class<T> type){
	//处理自定义mapper实现类型
  	if(type.isAnnotationPresent(MapperAnnotation.class)){
  		//MapperProxyFactory.class
		//MapperProxy.class
		MapperAnnotation tag = type.getAnnotation(MapperAnnotation.class);
  		logger.info("customer-mapper:{},class:{}",tag.value(),tag.impl().getName());
		return (T)Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type},
			(Object proxy, Method method, Object[] args) ->{
				proxy = BeanContext.getBean(tag.impl());
				return method.invoke(proxy,args);
			});
	}
	//mybatis默认实现方式
    return getSqlSession().getMapper(type);
  }
  • mapper声明改造
@MapperAnnotation(impl = DatasourceMapperImpl.class)
public interface DataSourceMapper {

达到的效果,mapper消费方无感知.接口声明无改动,达到切换实现类的目的。

  • 不足的地方
    mapper的实现类有两个,自定义实现加了@Primary标记。否则@Autowire引入的实现还是sqlSession动态代理生成的。
    动态代理能否排除一些不需要生成的mapper呢,源码里并没有发现,尚未细究。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值