mybatis通过代理模式产生mapper的代理类,jdk的动态代理
spring怎么把mybatis产生的代理对象注入到容器中?
- @MapperScan通过@Import引入MapperScannerRegistrar,这里采用@Import注解的第三种使用方式
- MapperScannerRegistrar类通过实现ImportBeanDefinitionRegistrar接口的registerBeanDefinitions方法把scan扫描到的类信息解析成beanDefinition放到beanDefinitionMap中,其中包括MapperFactoryBean,此类就是mybatis用来创建bean的factoryBean
- getSqlSseion通过jdk的动态代理返回mapper的代理对象,MethodProxy就是InvocationHandler接口的实现类,里面实现mapper的方法的具体逻辑
- mybatis插件原理
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(MapperScannerRegistrar.class)
public @interface MapperScan {
}
public class MapperFactoryBean<T> extends SqlSessionDaoSupport implements FactoryBean<T> {
/**
* {@inheritDoc}
*/
@Override
public T getObject() throws Exception {
return getSqlSession().getMapper(this.mapperInterface);
}
}
public class MapperProxyFactory<T> {
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
public MapperProxyFactory(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
}
public Class<T> getMapperInterface() {
return mapperInterface;
}
public Map<Method, MapperMethod> getMethodCache() {
return methodCache;
}
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
//这里即jdk动态代理的方法
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
public class MapperProxy<T> implements InvocationHandler, Serializable {
private static final long serialVersionUID = -6424540398559729838L;
private final SqlSession sqlSession;
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache;
public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
this.sqlSession = sqlSession;
this.mapperInterface = mapperInterface;
this.methodCache = methodCache;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else if (isDefaultMethod(method)) {
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}
- spring注入对象的方式
- @Bean
- FactoryBean spring提供的一个接口,用来手动创建bean,特点是可以自定义bean的创建过程
- api registrySingleton --beanFactory.registerSingleton()
- FactoryMethod
- beanfactory和factorybean
beanfactory spring的bean工厂,产生bean;
factorybean是个特殊的bean,需要实现FactoryBean接口的三个方法,getObject方法返回一个bean
-
@Import注解的三种使用方式总结
第一种用法:
@Import
({ 要导入的容器中的组件 } ):容器会自动注册这个组件,id默认是全类名
第二种用法:
ImportSelector
:返回需要导入的组件的全类名数组,springboot底层用的特别多【重点 】
第三种用法:
ImportBeanDefinitionRegistrar
:手动注册bean到容器
- spring加载类的大概过程:
jvm加载类信息===========>beandefinition========>put到 beandefinitionMap ==========通过beanDefinition的信息创建bean
参考Factorybean,BeanFactory,Spring扩展点和生命周期