@MapperScan
是 MyBatis 框架中的一个注解,用于简化 MyBatis Mapper 接口的扫描和注册过程。通过使用 @MapperScan
注解,可以避免在每个 Mapper 接口上单独添加 @Mapper
注解,从而提高开发效率和代码整洁度。以下是 @MapperScan
注解的作用和常见使用方式:
作用
- 自动扫描 Mapper 接口:
@MapperScan
注解用于指定一个或多个包路径,MyBatis 会自动扫描这些包路径下的所有 Mapper 接口,并将它们注册为 MyBatis 的 Mapper。 - 简化配置:通过集中配置 Mapper 接口的扫描路径,可以减少重复的
@Mapper
注解,使配置更加简洁。
常见使用方式
1. 基本用法
在 Spring Boot 应用的主类或配置类上使用 @MapperScan
注解,指定 Mapper 接口所在的包路径。
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
在上述示例中,@MapperScan("com.example.mapper")
指定了 com.example.mapper
包下的所有接口都会被 MyBatis 扫描并注册为 Mapper。
2. 指定多个包路径
如果 Mapper 接口分布在多个包中,可以使用数组形式指定多个包路径。
@SpringBootApplication
@MapperScan({"com.example.mapper", "com.example.another.mapper"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3. 使用通配符
可以使用通配符来指定包路径,例如 com.example.*.mapper
表示 com.example
包下所有子包中的 mapper
包。
@SpringBootApplication
@MapperScan("com.example.*.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4. 结合 MyBatis 配置文件
在某些情况下,可能需要结合 MyBatis 的 XML 配置文件使用 @MapperScan
注解。可以在配置类中指定 MyBatis 的配置文件路径。
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@MapperScan("com.example.mapper")
@ImportResource("classpath:mybatis-config.xml")
public class MyBatisConfig {
// 其他配置
}
在上述示例中,@ImportResource("classpath:mybatis-config.xml")
指定了 MyBatis 的 XML 配置文件路径。
总结
@MapperScan
注解是 MyBatis 提供的一个便捷工具,用于自动扫描和注册 Mapper 接口。通过在 Spring Boot 应用的主类或配置类上使用 @MapperScan
注解,可以简化 Mapper 接口的配置,提高开发效率。常见的使用方式包括指定单个包路径、多个包路径以及结合 MyBatis 配置文件使用。