从MapperScannerConfigurer看MyBatis自动扫描Mapper的机制(二)

2015-01-25 11:37:58 · 作者: · 浏览: 16
()); definition.setBeanClass(MapperFactoryBean.class); definition.getPropertyValues().add("addToConfig", this.addToConfig); boolean explicitFactoryUsed = false; if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) { definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(this.sqlSessionFactoryBeanName)); explicitFactoryUsed = true; } else if (this.sqlSessionFactory != null) { definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory); explicitFactoryUsed = true; } if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) { if (explicitFactoryUsed) { logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored."); } definition.getPropertyValues().add("sqlSessionTemplate", new RuntimeBeanReference(this.sqlSessionTemplateBeanName)); explicitFactoryUsed = true; } else if (this.sqlSessionTemplate != null) { if (explicitFactoryUsed) { logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored."); } definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate); explicitFactoryUsed = true; } if (!explicitFactoryUsed) { if (logger.isDebugEnabled()) { logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'."); } definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); } } } return beanDefinitions; }

第一步就能看到,调用了父类的doScan(...)方法,父类的doScan(..)这里就不放出来了,它是Spring自动扫描机制的核心,也就是我们注册:

  

这个东西会用到的,它可以帮我们自动注册@Controller、@Service等组件

本质上,也是通过扫描这些类,并将它们加入到BeanDefinition中,所以上面通过父类的doScan(...)方法其实是将我们设置的base-package下的类都封装成了BeanDefinition,并且添加到了一个Set集合中去了。也就是doScan(..)第一句得到的beanDefinitions。

但和父类略有不同的是,得到了所有的BeanDefinition之后,这并不真正要注入到容器中的类,还记得MyBatis手动把Mapper注入到Spring时是如何配置的吗:

  
  
   
  
   

  

而上面通过自动扫描注册的Mapper的BeanDefinition是类似这样的:

  

  

关键是这个class,所以需要转换,并将属性注入进去,mapperInterface和sqlSessionFactory都是必须的。

这样就完成了Mapper的自动扫描,不知道这样讲是否思路清晰~