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>
我是找不到 RedisTemplate
3. 解决方案
1).Service层必须要实现,实现类得@Service注解不要忘记
@Service导包要导正确:import org.springframework.stereotype.Service;
注意:Spring boot工程可以试试在启动类上加@MapperScan("Mapper/Dao层的包路径")注解。
注意:一定不要导阿里巴巴的,否则报错 importcom.alibaba.dubbo.config.annotation.Service;
2).降低Autowired检测的级别,将Severity的级别由之前的error改成warning或其它可以忽略的级别。
3)@Autowired写成@Autowired(required=false)
required属性:
@Autowired(required=true):当使用@Autowired注解的时候,其实默认就@Autowired(required=true),表示注入的时候,该bean必须存在,否则就会注入失败。
@Autowired(required=false):表示忽略当前要注入的bean,如果有直接注入,没有跳过,不会报错。
@ Autowired改成@Resource注解
4. 补充
Mapper/Dao层加上@Mapper然后还有错误提示
Service注入Mapper/Dao层时也会发生这样的错误,但不能用上面的解决方案,Mapper/Dao它里面的方法是映射sql.xml文件执行sql的接口所以没有实现不会用加@Service这个注解去解决。
1)@ Autowired改成@Resource注解
2)Mapper/Dao层的接口上加上@Repository注解
转 : https://blog.csdn.net/WYP123456L/article/details/122479993
https://www.jb51.net/article/154488.htm
- autowire 错误 Could beans foundautowire could found beans autowire错误could beans xxxservice autowire could found addressbookservice autowire could beans autowire bookdao could beans autowire方法could beans required integer could found service mysql could found qapplication错误found file configuration management错误found