赞
踩
mybatis通过代理模式产生mapper的代理类,jdk的动态代理
spring怎么把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);
- }
beanfactory spring的bean工厂,产生bean;
factorybean是个特殊的bean,需要实现FactoryBean接口的三个方法,getObject方法返回一个bean
@Import注解的三种使用方式总结
第一种用法:
@Import
({ 要导入的容器中的组件 } ):容器会自动注册这个组件,id默认是全类名
第二种用法:
ImportSelector
:返回需要导入的组件的全类名数组,springboot底层用的特别多【重点 】
第三种用法:
ImportBeanDefinitionRegistrar
:手动注册bean到容器
jvm加载类信息===========>beandefinition========>put到 beandefinitionMap ==========通过beanDefinition的信息创建bean
参考Factorybean,BeanFactory,Spring扩展点和生命周期
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。