MyBatis Mapper 接口为何能像普通 Bean 一样被 @Autowired 自动注入?
摘要:MyBatis中的Mapper接口是如何变成Spring中的Bean对象的,本文将带你从源码角度进行分析!
案例
案例一: MyBatis单独使用
在 resources 目录下新建 mybatis-config.xml 配置文件,文件内容如下:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--配置日志-->
<settings>
<setting name="logImpl" value="LOG4J2"/>
</settings>
<!--配置数据源和事务管理器-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/study"/>
<property name="username" value="root"/>
<property name="password" value="xxxxxx"/>
</dataSource>
</environment>
</environments>
<!--配置 mapper 文件的位置-->
<mappers>
<mapper resource="com/study/mybatis/UserMapper.xml"/>
</mappers>
</configuration>
在 resources 下面的 com/study/mybatis 文件夹中新建 UserMapper.xml 文件,文件内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.study.mybatis.mapper.UserMapper">
<select id="getUserById" resultType="com.study.mybatis.entity.User">
select * from User where id = #{id}
</select>
</mapper>
同时在对应层级的 package 下新建 UserMapper 接口,该接口中包含一个 getUserById() 方法和 UserMapper.xml 文件中配置的相对应。代码如下:
@Mapper
public interface UserMapper {
User getUserById(@Param("id") Long id);
}
然后在 Java 代码中,可以通过现构造 SqlSessionFactory 对象,从这个对象中获取一个 SqlSession 对象,然后再通过它获取到 UserMapper 接口的动态代理对象,然后通过这个动态代理对象来调用对应的方法。
