写在前面

在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("一起学服务启动成功...");
    }
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐