一、问题引出
在mybatis中,mapper都是像以下一个个的接口:
public interface UserMapper {
long countByExample(UserDTOExample example);
int deleteByExample(UserDTOExample example);
int deleteByPrimaryKey(Integer id);
int insert(UserDTO record);
int insertSelective(UserDTO record);
List<UserDTO> selectByExample(UserDTOExample example);
UserDTO selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") UserDTO record, @Param("example") UserDTOExample example);
int updateByExample(@Param("record") UserDTO record, @Param("example") UserDTOExample example);
int updateByPrimaryKeySelective(UserDTO record);
int updateByPrimaryKey(UserDTO record);
}
public interface UserMapperExt extends UserMapper {
List<UserDTO> findUserListByName(String username);
}
但是在使用的时候,都是通过spring bean注入的方式使用的,如下:
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserMapperExt userMapperExt;
@GetMapping("get-userInfo")
public String getUserInfo() {
List<UserDTO> userList = userMapperExt.findUserListByName("ZHANGSAN");
return "SUCCESS";
}
}
那么,mybatis的mapper接口(例如:接口UserMapperExt)是怎么样被实例化为spring bean的呢?
二、mybatis mapper接口被转为spring bean的过程
mybatis mapper接口被初始化为spring bean大体分三步:
加载mybatis mapper bean的注册器MapperScannerRegistrar---》MapperScannerRegistrar加载@MapperScan指定包路径下面的接口为bean并注册到容器中---》将mybatis mapper bean与动态代理实现MapperProxy关联起来。
流程图如下:
三、注册器MapperScannerRegistrar加载
启动类代码如下:
package com.iwill.mybatis;
import org.mybatis.spring.annotation.