您的位置:首页 > 编程语言

Mybatis实现【7】 --基于接口编程的原理

2014-06-18 16:31 465 查看
MyBatis可以仅通过申明接口并在annotation上注明sql,即可省略配置文件的编写。

这里Mapper是不需要实现类,我们来探究下MyBatis是如何做这层代理的。

bean的注入

1、声明需要注入的包

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--basePackage指定要扫描的包,可指定多个包,包与包之间用逗号或分号分隔-->
<property name="basePackage" value="com.cyou.fz.*.*.dao,com.cyou.fz.*.*.*.dao,com.cyou.fz.*.*.*.*.dao"/>
</bean>

MapperScannerConfig类描述是:

//BeanDefinitionRegistryPostProcessor that searches recursively starting from a base package for
* interfaces and registers them as MapperFactoryBean. Note that only interfaces with at
* least one method will be registered; concrete classes will be ignored

MapperScannerConfigurer的Scanner类负责搜索basePackage类下所有的MapperClass并将其注册至spring的beanfinitionHolder中,其注册的classBean为MapperFactoryBean。

1.1、与Spring框架整合注入Bean

MapperScannerConfigurer通过BeanDefinitionRegistryPostProcessor并实现postProcessBeanDefinitionRegistry(...)方法,在Spring初始化时候将Bean及该Bean的一些属性信息(scope、className、beanName等)保存至BeanDefinitionHolder中。

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
if (this.processPropertyPlaceHolders) {
processPropertyPlaceHolders();
}

ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
//...
scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
}

实际上调用ClassPathMapperScanner的doscan()方法扫描包并注册

public Set<BeanDefinitionHolder> doScan(String... basePackages) {
//在super.doScan()中将所有Mapper接口的class注册至BeanDefinitionHolder并放回一个set对象
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 {
for (BeanDefinitionHolder holder : beanDefinitions) {
GenericBeanDefinition 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
definition.getPropertyValues().add("mapperInterface", definition.getBeanClassName());
definition.setBeanClass(MapperFactoryBean.class);

///...
return beanDefinitions;
}

MapperFactoryBean直接实现了Spring的FactoryBean及InitializingBean接口,作为专门生产Mapper实例的工厂

1.2、通过MapperFactoryBean获取Mapper实例

1.2.1、在创建Mapper实例时,首先在MapperFactoryBean中执行afterPropertiesSet():

public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException {
// Let abstract subclasses check their configuration.
checkDaoConfig();

//...
}

checkDaoConfig()如下:

//检测当前需要创建的mapperInterface在Configuration中是否存在,不存在则添加
protected void checkDaoConfig() {
super.checkDaoConfig();

notNull(this.mapperInterface, "Property 'mapperInterface' is required");

Configuration configuration = getSqlSession().getConfiguration();
if (this.addToConfig && !configuration.hasMapper(this.mapperInterface)) {
try {
configuration.addMapper(this.mapperInterface);
} catch (Throwable t) {
logger.error("Error while adding the mapper '" + this.mapperInterface + "' to configuration.", t);
throw new IllegalArgumentException(t);
} finally {
ErrorContext.instance().reset();
}
}
}

1.2.2、获取Mapper实例

在执行完afterPropertiesSet()方法后,执行getObject()方法来获得Mapper实例:

public T getObject() throws Exception {
return getSqlSession().getMapper(this.mapperInterface);
}

通过调用链,最终调用MapperRegistry的getMapper()方法:

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
//这里的knowMappers保存之前afterPropertiesSet中保存进来的mapperInterface
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null)
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
try {
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}

在mapperProxyFactory的newInstance中:

public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}

这里创建了MapperProxy对象。并与“Mybatis实现【4】”中查询的执行过程对接起来。

该系列文章参考如下书籍及文章:

《Java Persistence with MyBatis 》

《http://www.cnblogs.com/hzhuxin/p/3349836.html》

《http://www.iteye.com/topic/1112327》

《http://www.iteye.com/blogs/subjects/mybatis_internals》

《http://denger.me/2011/05/mybatis-and-spring-interface-integrated/》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: