@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"})
-
當需要排除某些接口時(結合自定義過濾器)。
?
?