MyBatis是一款優(yōu)秀的持久層構(gòu)架唱凯,它支持定制化SQL語(yǔ)句悦陋、存儲(chǔ)過(guò)程以及高級(jí)映射巫俺,可以通過(guò)簡(jiǎn)單的XML或注解配置和映射原生信息,將POJOs映射成數(shù)據(jù)庫(kù)中的記錄纺棺,從而方便進(jìn)行增刪改查的操作(官網(wǎng))
問(wèn)題
Spring如何與MyBatis連接起來(lái)的榄笙?如何去獲取Mybatis中的Mapper,以及獲取Mapper時(shí)干了哪些騷操作邪狞?
為了弄清楚上述問(wèn)題祷蝌,菜菜首先貼出開(kāi)發(fā)時(shí)主要用到的MyBatis配置,隨后進(jìn)行源碼解讀帆卓,本文采用的是注解式配置巨朦。
一般MyBatis的配置如下所示:
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@PropertySource({"classpath:jdbc.properties"})
@MapperScan(basePackages = "me.ele.eliter.**.mapper")
public class MyBatisConfig {
private static final Log LOG = LogFactory.getLog(MyBatisConfig.class);
@Bean(destroyMethod = "close")
public DataSource dataSource(
@Value("${db.driver}") String driverClass,
@Value("${db.url}") String jdbcUrl,
@Value("${db.username}") String userName,
@Value("${db.password}") String passWord) throws Exception {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driverClass);
dataSource.setJdbcUrl(jdbcUrl);
dataSource.setUser(userName);
dataSource.setPassword(passWord);
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
dataSourceTransactionManager.afterPropertiesSet();
return dataSourceTransactionManager;
}
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource, ApplicationContext applicationContext) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setConfigLocation(applicationContext.getResource("classpath:mybatis-config.xml"));
sessionFactory.afterPropertiesSet();
sessionFactory.setPlugins(new Interceptor[] { new PagerInterceptor()});
return sessionFactory;
}
@Bean
public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) throws Exception {
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.afterPropertiesSet();
return transactionTemplate;
}
}
可以看到MyBatisConfig這個(gè)類(lèi)上有幾個(gè)重要的注解@Configuration與@MapperScan,
@Configuration是Spring中注解,主要說(shuō)明該類(lèi)是配置類(lèi)剑令,Spring在啟動(dòng)時(shí)會(huì)執(zhí)行@Bean的方法糊啡,并進(jìn)行Bean的定義,詳細(xì)信息請(qǐng)自行搜索吁津。
本文主要講@MapperScan棚蓄,首先看MapperScan的定義如下
接下來(lái)看MyBatis掃描干了些什么事役拴?以及如何將這些BeanDefinition注冊(cè)到IOC容器中。
以下是MapperScannerRegistrar實(shí)現(xiàn)registerBeanDefinitions的源碼
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
//1.獲取了注解MapperScan中的信息
AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(MapperScan.class.getName()));
/*2.將Spring中的registry放入scanner中钾埂,ClassPathMapperScanner繼承了Spring的ClassPathBeanDefinitionScanner河闰,
在new 的時(shí)候調(diào)用了ClassPathBeanDefinitionScanner的構(gòu)造方法,將register傳入了ClassPathBeanDefinitionScanner中
*/
ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
//3.一些屬性設(shè)置操作
// this check is needed in Spring 3.1
if (resourceLoader != null) {
scanner.setResourceLoader(resourceLoader);
}
Class<? extends Annotation> annotationClass = annoAttrs.getClass("annotationClass");
if (!Annotation.class.equals(annotationClass)) {
scanner.setAnnotationClass(annotationClass);
}
Class<?> markerInterface = annoAttrs.getClass("markerInterface");
if (!Class.class.equals(markerInterface)) {
scanner.setMarkerInterface(markerInterface);
}
Class<? extends BeanNameGenerator> generatorClass = annoAttrs.getClass("nameGenerator");
if (!BeanNameGenerator.class.equals(generatorClass)) {
scanner.setBeanNameGenerator(BeanUtils.instantiateClass(generatorClass));
}
Class<? extends MapperFactoryBean> mapperFactoryBeanClass = annoAttrs.getClass("factoryBean");
if (!MapperFactoryBean.class.equals(mapperFactoryBeanClass)) {
scanner.setMapperFactoryBean(BeanUtils.instantiateClass(mapperFactoryBeanClass));
}
scanner.setSqlSessionTemplateBeanName(annoAttrs.getString("sqlSessionTemplateRef"));
scanner.setSqlSessionFactoryBeanName(annoAttrs.getString("sqlSessionFactoryRef"));
List<String> basePackages = new ArrayList<String>();
for (String pkg : annoAttrs.getStringArray("value")) {
if (StringUtils.hasText(pkg)) {
basePackages.add(pkg);
}
}
for (String pkg : annoAttrs.getStringArray("basePackages")) {
if (StringUtils.hasText(pkg)) {
basePackages.add(pkg);
}
}
for (Class<?> clazz : annoAttrs.getClassArray("basePackageClasses")) {
basePackages.add(ClassUtils.getPackageName(clazz));
}
scanner.registerFilters();
//4.具體執(zhí)行掃描
scanner.doScan(StringUtils.toStringArray(basePackages));
}
從上面源碼中可以看到在Spring調(diào)用registerBeanDefinitions時(shí)傳入了BeanDefinitionRegistry(registry),有了registry就可以將MyBatis中的Mapper的BeanDefinition信息注冊(cè)到Spring的IOC容器中褥紫,下面具體看下registerBeanDefinitions源碼姜性,首先是獲取了MapperScan注解中的屬性信息,接著將Sping中的register傳入scanner,這樣可將scanner掃描到的BeanDefinition信息注冊(cè)到IOC容器中髓考,最后是具體的掃描操作部念,下面看下ClassPathMapperScanner中具體掃描操作的源碼
@Override
public Set<BeanDefinitionHolder> doScan(String... basePackages) {
/*首先調(diào)用了Spring中的ClassPathBeanDefinitionScanner掃描類(lèi)進(jìn)行掃描得到了具體的beanDefinitions信息,
這一步也將掃描到的beanDefinitions信息注冊(cè)到了Spring的IOC容器中绳军,這里就不進(jìn)入Spring源碼看了*/
Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
if (beanDefinitions.isEmpty()) {
logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");
} else {
//這里是MyBatis對(duì)這些BeanDefinition做了一系列操作為MyBatis的特性服務(wù)
processBeanDefinitions(beanDefinitions);
}
return beanDefinitions;
}
private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
GenericBeanDefinition definition;
for (BeanDefinitionHolder holder : beanDefinitions) {
definition = (GenericBeanDefinition) holder.getBeanDefinition();
if (logger.isDebugEnabled()) {
logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName()
+ "' and '" + definition.getBeanClassName() + "' mapperInterface");
}
// the mapper interface is the original class of the bean
// but, the actual class of the bean is MapperFactoryBean
/*這里獲取到的是Mapper的接口印机,設(shè)置這些Mapper接口的實(shí)現(xiàn)類(lèi)默認(rèn)為MapperFactoryBean,偷天換日门驾,
(非常重要)下一篇文章中說(shuō)明為什么Mapper不用寫(xiě)接口實(shí)現(xiàn)類(lèi)就能運(yùn)行會(huì)再次講到這*/
definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59
definition.setBeanClass(this.mapperFactoryBean.getClass());
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() + "'.");
}
//這里設(shè)置Bean中的屬性自動(dòng)根據(jù)Type注入
//(非常重要射赛,后面的一些屬性的注入, 如sqlSessionFactory會(huì)自動(dòng)注入全仗于此)
definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
}
}
}
ClassPathMapperScanner繼承了Spring的ClassPathBeanDefinitionScanner,doScan方法
1.調(diào)用了ClassPathBeanDefinitionScanner里的doScan方法(掃描方式與Spring的掃描一致)奶是,以上MapperScannerRegistrar源碼注釋2說(shuō)明了ClassPathBeanDefinitionScanner擁有了Spring的register,這樣在得到MyBatis的Mapper后楣责,就可將其中的BeanDefinition注冊(cè)到Spring中竣灌。
2.通過(guò)調(diào)用processBeanDefinitions對(duì)BeanDefinition做了一些重要處理
2.1 definition.setBeanClass(this.mapperFactoryBean.getClass())設(shè)置Mapper接口的class對(duì)象或是類(lèi)的全限定名為MapperFactoryBean(可以理解為實(shí)現(xiàn)是MapperFactoryBean),這里是MyBatis只用寫(xiě)接口不用寫(xiě)實(shí)現(xiàn)的第一步,具體做是通過(guò)JDK動(dòng)態(tài)代理秆麸,具體細(xì)節(jié)見(jiàn)Mybatis源碼解析之MapperProxy
2.2 definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE設(shè)置了這個(gè)bean中的屬性是根據(jù)Type自動(dòng)注入初嘹,加上2.1后這個(gè)也就是說(shuō)會(huì)自動(dòng)調(diào)用MapperFactoryBean中的set方法,sqlSessionFactory就是通過(guò)這種方式注入的沮趣,進(jìn)而得到sqlSesion,這方面的詳細(xì)信息見(jiàn)Mybatis源碼解析之SqlSession來(lái)自何方
至此屯烦,Spring中已經(jīng)獲取到了MyBatis有哪些mapper,并且這些mapper接口的BeanDefinition信息經(jīng)過(guò)了MaBatis的處理房铭,比如設(shè)置接口的默認(rèn)實(shí)現(xiàn)類(lèi)為MapperFactoryBean等等驻龟,下一步就是解析MaBatis中配置的xml信息
如有錯(cuò)誤,歡迎各位大佬斧正缸匪!
[下一篇]:Mybatis源碼解析之配置解析