Invalid bound statement (not found) 的解决方案

{@org.springframework.beans.factory.annotation.Autowired(required=true)}

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.dao.StudentDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {
    
    @org.springframework.beans.factory.annotation.Autowired(required=true)}
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1790) ~[spring-beans-5.3.4.jar:5.3.4]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1346) ~[spring-beans-5.3.4.jar:5.3.4]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300) ~[spring-beans-5.3.4.jar:5.3.4]
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:657) ~[spring-beans-5.3.4.jar:5.3.4]
	... 35 common frames omitted

报错原因

通过报错信息可以看到spring容器在类自动加载的时候发现不到'com.example.demo.dao.StudentDao'这个包的信息,所以会提示{@org.springframework.beans.factory.annotation.Autowired(required=true)}

这句话的意思是:当spring容器在类加载的时候,spring容器没有发现这个包'com.example.demo.dao.StudentDao',或者说是找不到这个包文件。所以我们在控制层加入@Autowired注解,从spring容器中自动化注入这个包下面的类文件com.example.demo.dao.StudentDao,因为这个包文件没有添加到spring容器中,所以说根本找不到这个包,就会产生报错

解决办法

  • 情景一
	<resource>
        <directory>${basedir}/src/main/resources</directory>
        <filtering>true</filtering>
        <includes>
          <include>**/application*.yml</include>
          <include>**/application*.yaml</include>
          <include>**/application*.properties</include>
        </includes>
      </resource>

可以看到spring boot默认配置所有的资源都指向了resources 目录下,所以存放mapper.xml文件的包要放在该目录下。

  • 情景二

将存放mapper.xml文件的包放到/src/main/java目录下,这个时候我们就需要重新在pom.xml文件配置资源扫描的地址。

	<build>
       <resources>
            <resource>
                <!--工程目录-->
                <directory>src/main/java</directory>
                <!--工程包文件-->
                <includes>
                    <include>com/jwt/demo/db/xml/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

** 不管mapper包文件放到哪里,都需要以下两种配置的一种。*
1、在mapper层中加入@Mapper注解,这样做将该mapper 接口加载到spring容器中。
2、或者,在配置类或者启动类中加入@MapperScan(),在spring容器加载资源的时候,把指定位置的包注入到spring容器中。
3、最后在application.yaml配置文件中配置mapper的扫描

mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml	#指定扫描包路径

猜你喜欢

转载自blog.csdn.net/CSDN_java1005/article/details/114299340