• 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呢,源码里并没有发现,尚未细究。
  • 相关阅读:
    feign远程调用问题
    java8--stream
    feign业务组件远程请求 /oauth/token
    redis实现自增序列
    MySQL数据库 相关知识点
    netty
    spring的启动流程及bean的生命周期
    MethodHandleVS反射
    并发与并行
    关于注解的思考
  • 原文地址:https://www.cnblogs.com/coding-now/p/14660572.html
Copyright © 2020-2023  润新知