工程結構
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放在啓動類所在包或其子包下