2021.1 版 IDEA 使用 @MapperScan ,出现 Could not autowire

最近在使用springboot 整合mybatis 中出现了一个奇怪的问题,使用@MapperScan("mapper包路径"),在其它的类中使用@Autowire mapper 实现类会出现 Could not autowire ,的红色提示,但是可用正常使用注入对象;

启动类

package com.example.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages = "com.example.demo.mapper")
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

测试

package com.example.demo;

import com.example.demo.domain.User;
import com.example.demo.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class DemoApplicationTests {
    @Autowired
    private UserMapper userMapper;
    @Test
    void contextLoads() {
        User user=userMapper.findUserByName("张三");
        System.out.println(user);
    }

}

image.png

但是能够正常执行

image.png

而在UserMapper 上直接添加@Mapper 则不会有could not autowire 的提示;

package com.example.demo.mapper;

import com.example.demo.domain.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper {
    User findUserByName(String name);
}

image.png

这是什么原因呢?

阅读 7.1k
2 个回答

mybatis 自己处理了 mapper bean 的生成。

如果不加 @Mapper 的过程如下:

  1. mybatis 根据 @MapperScan 的包路径找到所有符合条件的 mapper
  2. 获取 spring bean 管理方面的 bean,通过代码直接把 mapper 注入进去
  3. 这时候 Autowired 就能够使用了

至于为什么 Autowired 报错,这是因为 IDEA 没有处理 @MapperScan 这个注解,没有去扫描 mapper 是否是一个合格的 bean。这样做也是合理的,@MapperScan 在 spring 这个体系中才有点显得格格不入,不过这也是因为它要去获取 xml 的原因。

当你加上 @Mapper 之后,IDEA 就能够知道它是一个 bean了,当然也就不报错了。

新手上路,请多包涵

idea没认出userMapper,所以要加上@Repository或@Mapper告诉idea这是个spring的component

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题