SpringBoot注解@MapperScan的實現(xiàn)
@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
會觸發(fā)MapperScannerRegistrar
,掃描指定包下的接口。為每個 Mapper 接口生成代理對象(通過 JDK 動態(tài)代理或 CGLIB),并注冊到 Spring 容器。
代理對象會綁定對應的 SQL(XML 或注解方式),執(zhí)行數(shù)據(jù)庫操作。
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"})
當需要排除某些接口時(結(jié)合自定義過濾器)。
到此這篇關于SpringBoot注解@MapperScan的實現(xiàn)的文章就介紹到這了,更多相關SpringBoot @MapperScan內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java如何實現(xiàn)N叉樹數(shù)據(jù)結(jié)構(gòu)
這篇文章主要介紹了Java如何實現(xiàn)N叉樹數(shù)據(jù)結(jié)構(gòu)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05一文詳解SpringBoot如何使用pageHelper做分頁處理
分頁是常見大型項目都需要的一個功能,PageHelper是一個非常流行的MyBatis分頁插件,下面就跟隨小編一起來了解下SpringBoot是如何使用pageHelper做分頁處理的吧2025-03-03Java 實戰(zhàn)項目之家居購物商城系統(tǒng)詳解流程
讀萬卷書不如行萬里路,只學書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用Java實現(xiàn)一個家居購物商城系統(tǒng),大家可以在過程中查缺補漏,提升水平2021-11-11