十分钟了解 @MapperScan
@MapperScan
是 MyBatis 和 MyBatis-Plus 提供的一个 Spring Boot 注解,用于自动扫描并注册 Mapper 接口,使其能够被 Spring 容器管理,并与对应的 XML 或注解 SQL 绑定。它的核心作用是简化 MyBatis Mapper 接口的配置,避免手动逐个声明。
1. 基本用法
(1)在启动类上添加 @MapperScan
@SpringBootApplication
@MapperScan("com.example.mapper") // 指定 Mapper 接口所在的包
public class MyApplication {public static void main(String[] args) {SpringApplication.run(MyApplication.class, args);}
}
-
作用:Spring 会扫描
com.example.mapper
包及其子包下的所有 Mapper 接口,并自动注册为 Bean。
(2)扫描多个包
@MapperScan({"com.example.mapper", "com.another.dao"})
-
可以传入多个包路径,适用于 Mapper 分散在不同模块的情况。
2. @MapperScan
的底层原理
-
Spring 启动时,
@MapperScan
会触发MapperScannerRegistrar
,扫描指定包下的接口。 -
为每个 Mapper 接口生成代理对象(通过 JDK 动态代理或 CGLIB),并注册到 Spring 容器。
-
代理对象会绑定对应的 SQL(XML 或注解方式),执行数据库操作。
3. 一定需要@MapperScan吗?
1. 什么情况下可以不用 @MapperScan
?
(1) 使用 MyBatis 的 <mapper>
接口手动注册
如果你在 MyBatis 的全局配置文件(如 mybatis-config.xml
)中手动注册了 Mapper 接口,例如:
<mappers><mapper class="com.example.dao.UserDao"/>
</mappers>
则不需要 @MapperScan
。但这种方式在 Spring Boot 中很少用。
(2) 使用 @Mapper
注解标记每个 DAO 接口
如果每个 Mapper 接口都添加了 @Mapper
注解(MyBatis 提供的注解),Spring Boot 会自动扫描它们:
@Mapper // 关键注解
public interface UserDao {User selectById(Long id);
}
此时不需要 @MapperScan
,但需确保:
-
接口所在的包路径被 Spring Boot 主类默认扫描(即与启动类同级或子包)。
-
项目中不存在其他冲突配置。
2. 什么情况下必须用 @MapperScan
?
(1) 未使用 @Mapper
注解
如果 DAO 接口没有逐个添加 @Mapper
注解,必须通过 @MapperScan
批量指定扫描路径:
@SpringBootApplication
@MapperScan("com.example.dao") // 指定 DAO 接口所在的包
public class App {public static void main(String[] args) {SpringApplication.run(App.class, args);}
}
(2) 需要灵活控制扫描范围
-
当 DAO 接口分散在多个包中时:
@MapperScan({"com.example.dao", "com.another.package.dao"})
-
当需要排除某些接口时(结合自定义过滤器)。