工程结构
SpringBoot应用默认扫描启动类所在包及其子包
这样的结构如果不使用MapperScan注解是无法扫描到UserMapper的。
使用@Autowired启动会报错
Field userMapper in com.neusiri.controller.HelloController required a bean of type 'com.neusiri.mapper.UserMapper' that could not be found.原因:
Mybatis自动配置类中存在一个AutoConfiguredMapperScannerRegistrar类,用来扫描标注类@mapper注解的类
/** * This will just scan the same base package as Spring Boot does. If you want * more power, you can explicitly use * {@link org.mybatis.spring.annotation.MapperScan} but this will get typed * mappers working correctly, out-of-the-box, similar to using Spring Data JPA * repositories. */ public static class AutoConfiguredMapperScannerRegistrar implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware { }源码中的这个类注解上解释了 ,使用SpringBoot基本包扫描,不使用@MapperScan时,这个类会生效(使用@MapperScan该类不会执行),会扫描启动类所在包及其子包中的mapper,我的mapper并不在里面,所以无法扫描到Mapper。
解决方法:
1、使用MapperScan注解扫描mapper(使用MapperScan Mapper类上可以不加@Mapper注解)
@SpringBootApplication @EnableSwagger2 @ComponentScan({"com.neusiri.controller","com.neusiri.config","com.neusiri.component","com.neusiri.mapper"}) @MapperScan({"com.neusiri.mapper"}) public class HelloWorldApplication { public static void main(String[] args) {2、 将Mapper放在启动类所在包或其子包下