IDEA报错:Could not autowire, No beans of XXX type Found

发布时间 2023-06-30 11:51:25作者: 古语云

1、问题描述:

      在Idea的spring工程里,经常会遇到 Could not autowire. No beans of 'xxxx' type found 的错误提示。(但程序的编译和运行都是没有问题的,有时候也有可能会报错,无法运行程序),这个错误提示并不会产生影响。对于程序员红色的错误提示看起来很不舒服。如下图:

2. 问题原因

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

  第一种原因,spring auto scan配置,在编辑情况下,无法找不到对应的bean,于是提示找不到对应bean的错误。常见于mybatis的mapper,如下:

<!-- mapper scanner configurer -->
<bean id="mapperScannerConfig" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.adu.spring_test.mybatis.dao" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>

3. 解决方案
(1)Service层必须要实现,实现类得@Service注解不要忘记

@Service导包要导正确:import org.springframework.stereotype.Service;

错误导包 :import com.alibaba.dubbo.config.annotation.Service;
正确的包: import org.springframework.stereotype.Service;

注意:Spring boot工程可以试试在启动类上加@MapperScan("Mapper/Dao层的包路径")注解。

注意:一定不要导阿里巴巴的包:importcom.alibaba.dubbo.config.annotation.Service; 否则报错 ​​​​​​​ 

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

我的IDEA版本:IntelliJ IDEA 2022.3.3 (Ultimate Edition)

老版本的IDEA 如下图:

 (3)@Autowired写成@Autowired(required=false)

required属性:

@Autowired(required=true):当使用@Autowired注解的时候,其实默认就@Autowired(required=true),表示注入的时候,该bean必须存在,否则就会注入失败。

@Autowired(required=false):表示忽略当前要注入的bean,如果有直接注入,没有跳过,不会报错。

4、最终效果:
我是通过方式二:【降低Autowired检测的级别,将Severity的级别由之前的error改成warning或其它可以忽略的级别。】 解决的,效果见下图!