SpringBoot - @Mapper与@MapperScan注解的作用是什么?

写在前面

在SpringBoot的项目中,集成Mybatis持久层框架后,对于Mybatis的接口类如:UserMapper,SysMenuMapper,这些接口类Mapper用于访问持久层,在JPA中指的是DAO层。在Service层需要使用@Autowired或@Resource注解注入后调用Mapper里的方法时,需要将这些接口注入到Spring上下文中。有两种方法可以完成注入:
在每个类*Mapper的接口上都加一个@Mapper注解。
在SpringBoot的启动类上加一个@MapperScan并指明包路径。

使用区别

@Mapper与@MapperScan 不能同时使用,否则@Mapper注解不起作用。

方法一:使用@Mapper

直接在每个对应的Mapper类上面添加注解@Mapper。Mapper类较多时,这样使用比较麻烦。
@Mapper
public interface IssueMapper {
    /**
     * 查询试题
     *
     * @param issueId 试题ID
     * @return 试题
     */
    public Issue selectIssueById(Long issueId);
}

方法二:使用扫描注解@MapperScan

在每个模块对应的启动类上添加注解@MapperScan("com.hadoopx.**.mapper")。
需要指明扫描包的范围,可以扫描1个或多个包,也可以扫描子包,需要通过通配符*或者**来指定。

①. 指定单个包:

@MapperScan("com.hadoopx.issue.mapper")
@SpringCloudApplication
public class ServicexYqxApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServicexYqxApplication.class, args);
        System.out.println("一起学服务启动成功...");
    }
}

②. 指定多个包:

@MapperScan({"com.hadoopx.issue.mapper","com.hadoopx.test.mapper","com.hadoopx.paper.mapper"})
@SpringCloudApplication
public class ServicexYqxApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServicexYqxApplication.class, args);
        System.out.println("一起学服务启动成功...");
    }
}

或者使用通配符:

// 一个*代表只能扫描任意单个包,无法递归扫描
@MapperScan("com.hadoopx.*.mapper")
@SpringCloudApplication
public class ServicexYqxApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServicexYqxApplication.class, args);
        System.out.println("一起学服务启动成功...");
    }
}
// 两个**代表可以扫描任意个包,可以递归扫描
@MapperScan("com.hadoopx.**.mapper")
@SpringCloudApplication
public class ServicexYqxApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServicexYqxApplication.class, args);
        System.out.println("一起学服务启动成功...");
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

cloneme01

谢谢您的支持与鼓励!

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

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

打赏作者

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

抵扣说明:

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

余额充值