一. 测试代码

//实体类
public class User {
private Integer id;
private String name;
private Integer age;
private String email;
private SexEnum sex;
//getter / setter
} public enum SexEnum { Male("Male", "男"), Female("Female", "女"); private String code; private String desc; SexEnum(String code, String desc){
this.code = code;
this.desc = desc;
}
} //Repository
@Repository
public interface UserMapper { public User getById(Integer id); public List<User> getByAge(Integer age); public int insert(User user);
} @SpringBootApplication
@MapperScan("com.study.demo.mybatis.mapper")
public class MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
}
} @Test
public void getById(){
System.out.println("getById 开始执行...");
User user = userMapper.getById(1);
System.out.println(user);
System.out.println("getById 结束执行...");
}

mapper.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.demo.mybatis.mapper.UserMapper">
<insert id="insert">
insert into user (name,age,email,sex) values(#{name}, #{age}, #{email}, #{sex})
</insert> <select id="getById" resultType="com.study.demo.mybatis.vo.User">
select * from user where id = #{id}
</select> <select id="getByAge" resultType="com.study.demo.mybatis.vo.User">
select * from user where age = #{age}
</select>
</mapper>

配置文件:

spring:
datasource:
#type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/deco?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false
username: root
password: 123456 mybatis:
mapper-locations: classpath:mapper/**Mapper.xml

@MapperScan("com.study.demo.mybatis.mapper") 主要做了两件事情:

1. 根据 "com.study.demo.mybatis.mapper" 配置进行mapper.java文件扫描.

  此处扫描到的就是 SchoolMapper.java 和 UserMapper.java 两个文件

2. 为扫描到的文件进行 BeanDefinition 注册

//关键代码: 
private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
GenericBeanDefinition definition;
for (BeanDefinitionHolder holder : beanDefinitions) {
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.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59
definition.setBeanClass(this.mapperFactoryBean.getClass());
......
}

在进入此方法之前,  beanDefinitions 已经通过扫描得到,

beanName beanClass
schoolMapper com.study.demo.mybatis.mapper.SchoolMapper
userMapper com.study.demo.mybatis.mapper.UserMapper

进入方法后, 会执行以下代码, 对 beanClass 进行重新赋值:

definition.setBeanClass(this.mapperFactoryBean.getClass());

这里的 mapperFactoryBean 是 ClassPathMapperScanner 的一个私有属性:

private MapperFactoryBean<?> mapperFactoryBean = new MapperFactoryBean<Object>();

也就是说, 后面对 beanName = userMapper 进行创建的时候, 会使用到  MapperFactoryBean

二. MapperFactoryBean

public class MapperFactoryBean<T> extends SqlSessionDaoSupport implements FactoryBean<T> {

  private Class<T> mapperInterface;

  private boolean addToConfig = true;

  public MapperFactoryBean() {
//intentionally empty
} public MapperFactoryBean(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
} /**
* {@inheritDoc}
*/
@Override
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 (Exception e) {
logger.error("Error while adding the mapper '" + this.mapperInterface + "' to configuration.", e);
throw new IllegalArgumentException(e);
} finally {
ErrorContext.instance().reset();
}
}
} /**
* {@inheritDoc}
*/
@Override
public T getObject() throws Exception {
return getSqlSession().getMapper(this.mapperInterface);
} /**
* {@inheritDoc}
*/
@Override
public Class<T> getObjectType() {
return this.mapperInterface;
} /**
* {@inheritDoc}
*/
@Override
public boolean isSingleton() {
return true;
} //------------- mutators -------------- /**
* Sets the mapper interface of the MyBatis mapper
*
* @param mapperInterface class of the interface
*/
public void setMapperInterface(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
} /**
* Return the mapper interface of the MyBatis mapper
*
* @return class of the interface
*/
public Class<T> getMapperInterface() {
return mapperInterface;
} /**
* If addToConfig is false the mapper will not be added to MyBatis. This means
* it must have been included in mybatis-config.xml.
* <p/>
* If it is true, the mapper will be added to MyBatis in the case it is not already
* registered.
* <p/>
* By default addToCofig is true.
*
* @param addToConfig
*/
public void setAddToConfig(boolean addToConfig) {
this.addToConfig = addToConfig;
} /**
* Return the flag for addition into MyBatis config.
*
* @return true if the mapper will be added to MyBatis in the case it is not already
* registered.
*/
public boolean isAddToConfig() {
return addToConfig;
}
}

从代码上看, 实现了 FactoryBean 接口,  他是一个 工厂bean.

在创建 userMapper 的时候, 就会调用 MapperFactoryBean 的 getObject() 方法.

md版本: https://files.cnblogs.com/files/elvinle/mybatis.zip

mybatis - @MapperScan的更多相关文章

  1. Mybatis——@MapperScan原理

    @MapperScan配置在@Configuration注解的类上会导入MapperScannerRegistrar类. 而MapperScannerRegistrar实现了ImportBeanDef ...

  2. SpringBoot 使用yml配置 mybatis+pagehelper+druid+freemarker实例

    SpringBoot 使用yml配置 mybatis+pagehelper+druid+freemarker实例 这是一个简单的SpringBoot整合实例 这里是项目的结构目录 首先是pom.xml ...

  3. Mybatis日志源码探究

    一.项目搭建 1.pom.xml <dependencies> <dependency> <groupId>log4j</groupId> <ar ...

  4. springboot和mybatis集成

    springboot和mybatis集成 pom  <?xml version="1.0" encoding="UTF-8"?> <proje ...

  5. springboot与缓存(redis,或者caffeine,guava)

    1.理论介绍 Java Caching定义了5个核心接口,分别是CachingProvider, CacheManager, Cache, Entry 和 Expiry. CachingProvide ...

  6. SpringBoot与Shiro的整合(单体式项目)

    1.包结构 2.jar包,配置文件,类 2.1pom.xml文件配置 <?xml version="1.0" encoding="UTF-8"?> ...

  7. Spring IOC Container原理解析

    Spring Framework 之 IOC IOC.DI基础概念 关于IOC和DI大家都不陌生,我们直接上martin fowler的原文,里面已经有DI的例子和spring的使用示例 <In ...

  8. Spring Boot MyBatis注解:@MapperScan和@Mapper

    最近参与公司的新项目架构搭建,在使用mybatis的注解时,和同时有了不同意见,同事认为使用@Mapper注解简单明了,而我建议使用@MapperScan,直接将mapper所在的目录扫描进去就行,而 ...

  9. 启动类加注解@MapperScan spring boot mybatis 启动错误

    Description: Field userDao in com.gcy.springsecuritydemo.service.user.UserService required a bean of ...

随机推荐

  1. VISIO 的一些技巧

    1.复制绘图 如果格式改变,在“设计”选项卡里将“将主题运用于新建的形状”前面的√去掉

  2. Uva10820 欧拉公式模板(求小于n且与n互素的数的个数)

    题意: 给出n,算出小于等于n的所有数中,有几对互质: 解法: 本质就是求有多少个2元组(x,y)满足:1 <= x,y <= n,且x与y互素. 除了(1,1)之外,其他所有的x和y都不 ...

  3. STL-queue 队列

    #include <iostream> #include <queue> using namespace std; int main() { // queue也很简单 // p ...

  4. Python 教你 4 行代码开发新闻网站通用爬虫

    \ ​ GNE(GeneralNewsExtractor)是一个通用新闻网站正文抽取模块,输入一篇新闻网页的 HTML, 输出正文内容.标题.作者.发布时间.正文中的图片地址和正文所在的标签源代码.G ...

  5. ng-辅助操作

    创建组件,指令,过滤器和服务 # 创建组件 ng generate component my-new-component # 创建组件别名 ng g component my-new-componen ...

  6. @Value注解没有起作用的梳理

    今天在使用@Value注解的时候遇到其不起作用的现象,先把场景说明一下:现在有A类和B类,而A类对象是通过new操作生成的临时对象,而B类对象是在A类中使用的:调试步骤如下: (1)将B类的属性字段都 ...

  7. IO流学习之字符流(一)

    IO流(Input/Output) 简介: 流是一种抽象概念,它代表了数据的无结构化传递.按照流的方式进行输入输出,数据被当成无结构的字节序或字符序列.从流中取得数据的操作称为提取操作,而向流中添加数 ...

  8. JAVA鼠标监听器

    package howework_07; public class Example9_10 { public static void main(String args[]) { WindowMouse ...

  9. [POI2010] GIL-Guilds - 二分图染色,DFS

    给一张无向图,要求你用黑白灰给点染色,且满足对于任意一个黑点,至少有一个白点和他相邻:对于任意一个白点,至少有一个黑点与他相邻,对于任意一个灰点,至少同时有一个黑点和白点和灰点与他相邻,问能否成功 S ...

  10. 【Linux远程连接工具】Xshell、Xftp家庭/学生版(免费使用)

    注:Xshell.Xftp家庭/学生版无需激活,可以免费使用! 1.步骤一: 官网下载地址:https://www.netsarang.com/zh/ 选择[所有下载]->[家庭/学校免费]   ...