@Mapper与@MapperScan

890 阅读1分钟

如何将Mapper接口加入容器

在SpringBoot的使用过程中,以MyBatis作为持久层的时候,向IOC容器中注入Mapper接口时有两种方法:

  1. 在Mapper接口上加@Mapper注解
  2. 在SpringBoot的主启动类上加@MapperScan(...)注解

@Mapper

@Mapper
public interface EmployeeMapper {
    @Select("SELECT * FROM employee WHERE id=#{id}")
    Employee getEmpById(Integer id);
}

此时在Service层使用@Autowired或@Resource注解就可以完成注入。

@MapperScan

@SpringBootApplication
@MapperScan("org.fall.springboot.dao")	// 主启动类上加@MapperScan扫描对应的Mapper接口的包
public class StudySpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(StudySpringBootApplication.class, args);
    }
}

自动注入时爆红?

当我们使用前面两种方式的其中之一时,会发现在注入时会爆红,但是运行却不影响使用: 解决的方法: 可以通过在Mapper接口上加 @Repository 注解来消除警告
原因:@Mapper、@MapperScan都是MyBatis提供的注解,而不是Spring自带的,在没有加@Repository注解时,IDEA自己误判还未将对应的实例放入IOC容器