1.问题描述

  在Idea的spring工程里,经常会遇到Could not autowire. No beans of 'xxxx' type found的错误提示。但程序的编译和运行都是没有问题的,这个错误提示并不会产生影响。但红色的错误提示在有些有强迫症的程序员眼里,多多少少有些不太舒服。

idea中springboot无法自动装配Could not autowire. No beans of 'xxx' type found

 

问题分析

在 Idea 的 spring 工程里,经常会遇到 Could not autowire. No beans of ‘xxxx' type found 的错误提示。但程序的编译和运行都是没有问题的,这个错误提示并不会产生影响。但红色的错误提示在有些有强迫症的程序员眼里,多多少少有些不太舒服。

原因可能有两个,第一个是IntellijIDEA本身工具的问题。第二个便是我们导入@Service包的时候导入包错误造成的

问题原因其一

第一个是 Intellij IDEA 本身工具的问题。

解决办法:

(1)不理它。

(2)加注解。

 

方案一 Autowired注解不是必须的

在自动转配的注解后面添加(required=false)

    
    @Autowired(required=false)
    public UserMapper userMapper;

@Autowired注解的时候,默认required=true,表示注入的时候bean必须存在,否则注入失败。

不太好,可能bean真不存在,就把正在的错误给过滤掉了。

方案二  降低 Autowired 检测的级别

降低 Autowired 检测的级别,将 Severity 的级别由之前的 error 改成 warning 或其它可以忽略的级别

idea中springboot无法自动装配Could not autowire. No beans of 'xxx' type found

 不太好,可能bean真不存在,就把正在的错误给过滤掉了。

方案三  @Component注解

在mapper文件上加@Component注解,把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class="">。

比如在UserMapper上面添加  @Component(value =“userMapper”)

idea中springboot无法自动装配Could not autowire. No beans of 'xxx' type found

虽然能解决红线的问题,
@Component注解,表明当需要创建类时,这个被注解的类是一个候选类。相当于类交给Spring管理,重新起个名字叫userMapper,但是并不推荐这样做。

方案四  @MapperScan注解

在SpringBoot中集成MyBatis,可以在mapper接口上添加@Mapper注解,将mapper注入到Spring。但是如果每一给mapper都添加@mapper注解会很麻烦!!!

启动类放在所有类外层,保证能扫描到所有子包。或者在启动类上添加扫描路径

@ComponentScan(basePackages = {"com.xxx"})

@ComponentScan(basePackageClasses= XXXController.class)

@SpringBootApplication(scanBasePackages={"com.xxx"})
 

这时可以使用@MapperScan注解来扫描包。
所以,一般在Application上面标注了MapperScan,全局自动扫描所有的Mapeper包中的mapper,如图所示。

@MapperScan(value = {"com.xxx.mapper"})指定包

idea中springboot无法自动装配Could not autowire. No beans of 'xxx' type found

方案五  @Repository注解

在mapper文件上加@Repository注解,这是从spring2.0新增的一个注解,用于简化 Spring 的开发,实现数据访问。

 

 

方案六 @Resource注解

更改@Autowired为@Resource

 

方案七 在服务层加上注解@Service

在服务层加上注解@Service或在mapper接口类上加上@Repository或@Component标签

确保包导入正确,@Service正确导入的是import org.springframework.stereotype.Service;

 

问题原因其二

针对第二种原因,解决方案当然是导入正确的包。首先我们来看下最容易导入的错误包,如下所示:

import com.alibaba.dubbo.config.annotation.Service;

正确的包应该是下面这个
import org.springframework.stereotype.Service;

 

 

 

 

相关文章:

  • 2021-08-13
  • 2021-11-22
  • 2021-05-31
  • 2021-06-29
  • 2021-08-11
  • 2021-04-25
  • 2021-08-27
  • 2021-06-04
猜你喜欢
  • 2021-07-19
  • 2021-12-10
  • 2021-06-21
  • 2022-12-23
  • 2021-09-16
  • 2021-05-20
  • 2022-12-23
相关资源
相似解决方案