java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot @MapperScan

SpringBoot注解@MapperScan的实现

作者:摆烂且佛系

@MapperScan是MyBatis和MyBatis-Plus提供的SpringBoot注解,用于自动扫描并注册 Mapper 接口,使其能够被 Spring 容器管理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

@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"})

2. @MapperScan 的底层原理

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,但需确保:

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"})

当需要排除某些接口时(结合自定义过滤器)。

到此这篇关于SpringBoot注解@MapperScan的实现的文章就介绍到这了,更多相关SpringBoot @MapperScan内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文