首页 > 解决方案 > Spring:使用来自 ibatis 库的 Java Mapper 时出错。接口不是 bean

问题描述

我正在使用 Java 和 Spring 框架开发一个后端应用程序。我从一个原型项目开始,但是在运行阶段会导致一些问题。我有这个界面:

@Mapper
public interface MyInterface {

    public ReturnType1 method1(long myLong);

    @Select("SELECT * FROM myTab WHERE id = #{myLong}")
    public ReturnType2 method2(long myLong);

    ...
    ...
}

该接口使用了ibatis库(类org.apache.ibatis.annotations.Mapper);在代码的其他地方我有这个服务:

@Service
public class ExampleService {

    @Autowired
    private MyInterface myInterface;

    ...
}

@Service注释在哪里org.springframework.stereotype.Service;。多亏了@Autowired,此服务使用具有@Mapper作为注释的接口(见前)。

但是,在运行阶段我收到以下错误:

应用程序启动失败:字段需要找不到myInterface类型的 bean 。MyInterface注入点有以下注解:@org.springframework.beans.factory.annotation.Autowired(required=true). MyInterface考虑在您的配置中定义一个 ' ' 类型的 bean 。

为什么会向我报告此错误?我不熟悉ibatis库......在我的项目中,我在这个路径中有一个 xml 文件:myProject/src/main/resources/mybatis/FileMapper.xml并且在 application.properties 文件中我有这一行:

mybatis.mapper-locations=classpath*:mybatis/*Mapper.xml

在我看来,一切都配置正确。你能向我解释一下我在哪里以及为什么会收到这个错误吗?

标签: javaspringspring-bootibatismapper

解决方案


你好添加@MapperScan

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

}


推荐阅读