0
点赞
收藏
分享

微信扫一扫

spring源码之模拟mybatis注入Mapper

c一段旅程c 2022-04-14 阅读 97

在mybatis官网中https://mybatis.org/spring/zh/mappers.html,我们可以看到,配置mapper映射可以在XML中进行。
在这里插入图片描述
那么这个原理我们可以看一下MapperFactoryBean的源码。
同样也是继承了FactoryBean这个类,实现了getObject方法和getObjectType方法。
与我们上一章写的FactoryBean方法注入mapper的时候是一样的。同样,也可以模拟一下这种通过XML来实现。

通过XML实现Mapper映射测试

@ComponentScan("com.spring.batis")
@ImportResource("classpath:spring.xml")
public class BatisConfig {

}


@Component
public class MyFactoryBean implements FactoryBean {

	Class mapperInterface;

	public void setMapperInterface(Class mapperInterface) {
		this.mapperInterface = mapperInterface;
	}

	@Override
	public Object getObject() throws Exception {
		Object mapper = MySqlSession.getMapper(mapperInterface);
		return mapper;
	}

	@Override
	public Class<?> getObjectType() {
		return mapperInterface;
	}
}

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


	<bean id="t" class="com.spring.batis.utils.MyFactoryBean">
		<property name="mapperInterface" value="com.spring.batis.dao.TMapper"/>
	</bean>
	<bean id="a" class="com.spring.batis.utils.MyFactoryBean">
		<property name="mapperInterface" value="com.spring.batis.dao.AMapper"/>
	</bean>

</beans>


	@Test
	public void customBatis(){
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BatisConfig.class);
		TMapper mapper = context.getBean(TMapper.class);
		mapper.queryMap("1");

		AMapper amapper = context.getBean(AMapper.class);
		amapper.queryMap("1");
	}

//打印结果
假装连接数据库
假装执行了查询语句select * from t where id = ${id}
假装返回了JSON串
假装连接数据库
假装执行了查询语句select * from a where id = ${id}
假装返回了JSON串

这个方式确实是实现了mapper的映射,但是,每一个mapper 都要配置一个,显然太笨重了。
于是呢mybatis又给了另外一种方式,直接扫描包下面的mapper文件,自动注入。
<mybatis:scan base-package=“org.mybatis.spring.sample.mapper” />
或者
@MapperScan(“org.mybatis.spring.sample.mapper”)
后面的文章就来解析一下这种扫描包的方式是如何一次性注入多个mapper的

举报

相关推荐

0 条评论