SpringBoot项目使用mybatis逆向工程生成的Mapper无法自动注入,报required a bean of 'xxx' that could not be found错误,求解决方案!

报错内容为

Field vulLibMapper in com.shtec.dataonweb.service.TestService required a bean of type 'com.shtec.dataonweb.dao.VulLibMapper' that could not be found.
The injection point has the following annotations:
@org.springframework.beans.factory.annotation.Autowired(required=true)



Service内容为

package com.shtec.dataonweb.service;
import com.shtec.dataonweb.bean.VulLibExample;
import com.shtec.dataonweb.dao.VulLibMapper;
import com.shtec.dataonweb.bean.VulLib;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class TestService {

    @Autowired
    VulLibMapper vulLibMapper;

    public VulLib testUpdated() {
        VulLibExample example = new VulLibExample();
        List<VulLib> list = vulLibMapper.selectByExample(example);
        return list.get(0);
    }
}



Mapper内容就不列出来了,都是根据generatorConfig.xml自动生成的,mybatis-generator-core的版本为1.3.4,mybatis-spring-boot-starter的版本为2.1.3,mybatis-generator-maven-plugin的版本为1.3.2。


很多方法都试过,给Mapper加@Repository无效。如果用@MapperScan则会报如下错误


nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required


我自己搞定了,原因是没配置application.yml内的mybatis配置,把xml文件和接口文件都放在一个包下,然后配置:

mybatis:
  mapper-locations: com.shtec.dataonweb.mapper.*.xml
  type-aliases-package: com.shtec.dataonweb.bean

再入口类加上@MapperScan("com.shtec.dataonweb.mapper")自动扫描。


最后在pom.xml的bulid里加上:

        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>

大功告成~

看service没用,看这句话:required a bean of type 'com.shtec.dataonweb.dao.VulLibMapper' that could not be found.意思是说你的service依赖的dao找不到,说明你的dao层类没有被代理到,这里要看看是否配置了这些参数:
1. 指定dao层的interface路径
2. 指定mapper.xml的路径
3. 是否配置了数据源,这里sessionFactory自动注入需要数据源的

exclude = {DataSourceAutoConfiguration.class}这个参数去掉试试

mybatis的配置呢

最好贴一下mapper文件,还有配置文件,单独的贴出来service是不能解决的

在类上加@Mapper注解

感觉是mapper没有注入成功,在注入的时候缺少sqlSessionFactory 或sqlSessionTemplate

怀疑1是mapper没有对应2.你mybatis的配置有问题