每天一个注解之@MapperScan

@MapperScan

@MapperScan 是 MyBatis-Spring 项目中的一个注解,用于指示 Spring 扫描并注册 MyBatis 的 Mapper 接口,使得这些接口可以被自动实例化并注入到 Spring 容器中。

在使用 MyBatis 时,通常会定义 Mapper 接口来描述 SQL 操作,而实际的 SQL 语句和参数映射是通过 XML 文件完成的。@MapperScan 注解的作用是告诉 Spring 扫描指定的包路径,查找这些包下的 Mapper 接口,并将它们注册到 Spring 容器中。

以下是一个简单的示例,展示了如何在 Spring Boot 项目中使用 @MapperScan 注解:

在 Spring Boot 项目的入口类上使用 @MapperScan 注解,指定需要扫描的 Mapper 接口所在的包路径:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@MapperScan("com.example.mapper")  // 指定 Mapper 接口所在的包路径
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

在上面的示例中,使用了 @MapperScan 注解,通过指定包路径 “com.example.mapper”,告诉 Spring 扫描该路径下的 Mapper 接口并注册到 Spring 容器中。

创建一个 Mapper 接口,用于定义 SQL 操作:

public interface UserMapper {

    User selectUserById(Long id);

    void insertUser(User user);

    // 其他方法...
}

在上面的示例中,创建了一个 UserMapper 接口,其中定义了一些方法,用于操作用户数据。

通过在 Spring Boot 项目中使用 @MapperScan 注解,可以将 MyBatis 的 Mapper 接口自动注册到 Spring 容器中,在业务代码中直接注入和使用这些 Mapper 接口,而无需手动实例化。这样可以方便地使用 MyBatis 进行数据库操作。

参数

value(String[] 类型):用于指定一个或多个需要扫描的包路径。可以使用 value 参数来代替 basePackages 参数,效果是相同的。示例如下:

@MapperScan("com.example.mapper")

或者:

@MapperScan(value = {"com.example.mapper"})

basePackages(String[] 类型):同样用于指定一个或多个需要扫描的包路径。可以使用数组来指定多个路径。示例如下:

@MapperScan(basePackages = {"com.example.mapper"})

basePackageClasses(Class<?>[] 类型):用于指定一个或多个类,Spring 将根据这些类所在的包来进行扫描。示例如下:

@MapperScan(basePackageClasses = {UserMapper.class})

annotationClass(Class<? extends Annotation> 类型):指定一个自定义的注解类,Spring 将扫描使用该注解标记的接口。默认情况下,会扫描带有 @Mapper 注解的接口。

markerInterface(Class<?> 类型):指定一个标记接口类,Spring 将扫描实现了该标记接口的接口。

nameGenerator(Class<? extends BeanNameGenerator> 类型):指定一个自定义的 Bean 名称生成器,用于生成 Mapper 接口的 Bean 名称。

通过指定这些参数,可以灵活地配置 @MapperScan 注解,使得 Spring 能够自动扫描并注册你指定的 Mapper 接口。注意,@MapperScan 只是一个 Spring 注解,其作用是为了方便 MyBatis Mapper 接口的自动扫描和注册,以及将它们转化为 Spring Bean,从而可以在业务代码中进行注入和使用。

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

羱滒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值