@MapperScan
注解是 MyBatis 提供的一个功能,用于自动扫描指定包下的 MyBatis Mapper 接口,并将它们注册到 Spring 容器中。这样,Spring Boot 应用程序在启动时能够自动识别并加载这些 Mapper。
@MapperScan
注解的作用
-
自动扫描和注册 Mapper:
@MapperScan
用于指定要扫描的包路径,自动扫描该路径下的 Mapper 接口,并将这些 Mapper 接口注册为 Spring 的 Bean。这使得你不需要手动声明每一个 Mapper 实例化,而是可以通过自动扫描来简化配置。
-
简化配置:
- 使用
@MapperScan
可以减少在 Spring Boot 应用中对@Mapper
注解的使用,同时使配置更加集中。
- 使用
如何配置 @MapperScan
在 Spring Boot 应用主类上配置
最常见的做法是将 @MapperScan
注解放在 Spring Boot 主应用类上,这样可以扫描整个应用程序的 Mapper 包。示例:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan("com.example.projectDemo.mapper") // 指定扫描的 Mapper 包路径
public class ProjectDemoApplication {
public static void main(String[] args) {
SpringApplication.run(ProjectDemoApplication.class, args);
}
}
在上面的示例中,@MapperScan("com.example.projectDemo.mapper")
表示扫描 com.example.projectDemo.mapper
包下的所有 Mapper 接口。
在配置类上配置
如果你希望将 Mapper 的扫描配置与其他配置分开,可以将 @MapperScan
放在一个配置类上。示例:
import org.springframework.context.annotation.Configuration;
import org.mybatis.spring.annotation.MapperScan;
@Configuration
@MapperScan("com.example.projectDemo.mapper") // 指定扫描的 Mapper 包路径
public class MyBatisConfig {
// 这里可以定义其他 MyBatis 配置
}
这种做法在大型应用中可能更有组织,特别是当你希望将 MyBatis 的配置与其他配置分开时。
常见配置选项
@MapperScan
注解有几个常用的配置选项:
basePackages
:指定要扫描的包路径。例如@MapperScan(basePackages = "com.example.projectDemo.mapper")
。basePackageClasses
:指定一个或多个类的包路径,MyBatis 将扫描这些类所在的包及其子包中的 Mapper 接口。例如@MapperScan(basePackageClasses = MyMapper.class)
。
示例
基本示例
假设你的 Mapper 接口位于 com.example.projectDemo.mapper
包中,你可以这样配置:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan("com.example.projectDemo.mapper") // 自动扫描 Mapper 接口
public class ProjectDemoApplication {
public static void main(String[] args) {
SpringApplication.run(ProjectDemoApplication.class, args);
}
}
使用 basePackages
和 basePackageClasses
import org.springframework.context.annotation.Configuration;
import org.mybatis.spring.annotation.MapperScan;
@Configuration
@MapperScan(basePackages = "com.example.projectDemo.mapper") // 使用 basePackages 扫描指定包
public class MyBatisConfig {
}
import org.springframework.context.annotation.Configuration;
import org.mybatis.spring.annotation.MapperScan;
@Configuration
@MapperScan(basePackageClasses = MyMapper.class) // 使用 basePackageClasses 扫描指定包
public class MyBatisConfig {
}
在这些示例中,com.example.projectDemo.mapper
是包含 MyBatis Mapper 接口的包路径。你需要根据实际情况将其替换为你项目中的实际包路径。
总结
@MapperScan
注解用于自动扫描 MyBatis Mapper 接口,并将其注册为 Spring Bean。通过在 Spring Boot 应用的主类或配置类上使用 @MapperScan
,可以简化 Mapper 的配置和管理。这使得项目结构更清晰,并减少了显式声明 Mapper 实例的需要。