SpringBoot+mybatis

初次接触springboot,只知道他采用了很多默认配置,自觉不用配置什么东西拿来用就行,就遇到了这样的问题:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.dao.UserDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup="", name="", description="", authenticationType=CONTAINER, type=java.lang.Object.class, mappedName="")}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1654) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1213) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:520) ~[spring-context-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:496) ~[spring-context-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:636) ~[spring-context-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:180) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessProperties(CommonAnnotationBeanPostProcessor.java:321) ~[spring-context-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    ... 57 common frames omitted

很显然mybatis没有根据接口和map.xml文件自动生成bean,那么问题就应该出在与mybatis有关的配置里面,但是springboot的配置实在太少了,少到一眼就看完,并且我也没发现有什么问题。:

一次偶然的机会我在一篇博客上看到了,人家写的springboot的启动类前边有个注解

@MapperScan("com.jy.affairs.mapper.*")

而我的是没有的,加上后果然不报错了。

值得一提的是:

如果将这个注解加到springboot的启动类上,那么它不仅对springboot本身生效,junit测试类也是可以运行的。

@SpringBootApplication
@MapperScan("com.example.demo.dao")
public class Demo1Application {
    public static void main(String[] args) {
        SpringApplication.run(Demo1Application.class, args);
    }
}

如果不加的话,在junit测试类的基类上加这个东西也行,但是这样只能使junit正常运行,springboot本身还是不行的

@RunWith(SpringRunner.class)
@SpringBootTest
@MapperScan("com.example.demo.dao")
public abstract class AbstractTest {

}

对这一现象我的猜测是@SpringBootTest这个注解隐式的引用了启动类上的@MapperScan这个注解

原文地址:https://www.cnblogs.com/liujinming/p/10709166.html