spring源码之模拟mybatis注入Mapper

在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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木小同

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值