whatya want from meIdea解决Couldnotautowire.Nobeansof‘xxxx‘typefou。。。
1.问题描述
  在Idea的spring⼯程⾥,经常会遇到Could not autowire. No beans of 'xxxx' type found的错误提⽰。(但程序的编译和运⾏都是没有问题的,有时候也有可能会报错,⽆法运⾏程序),这个错误提⽰并不会产⽣影响。但红⾊的错误提⽰看起来很不舒服。
2. 原因
原因可能有两个,第⼀个是IntellijIDEA本⾝⼯具的问题。第⼆个便是我们导⼊@Service包的时候导⼊包错误造成的
  第⼀种原因,spring auto scan配置,在编辑情况下,⽆法不到对应的bean,于是提⽰不到对应bean的错误。常见于mybatis的mapper,如下:
theonlyone<!-- mapper scanner configurer -->
<bean id="mapperScannerConfig" class="batis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.adu.batis.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
3. 解决⽅案
1).Service层必须要实现,实现类得@Service注解不要忘记
@Service导包要导正确:import org.springframework.stereotype.Service;
注意:Spring boot⼯程可以试试在启动类上加@MapperScan("Mapper/Dao层的包路径")注解。
注意:⼀定不要导阿⾥巴巴的,否则报错
importcom.fig.annotation.Service;
2).降低Autowired检测的级别,将Severity的级别由之前的error改成warning或其它可以忽略的级别。
happy new year to you
改变后:
gods and monsters4. 补充
Mapper/Dao层加上@Mapper然后还有错误提⽰
Service注⼊Mapper/Dao层时也会发⽣这样的错误,但不能⽤上⾯的解决⽅案,Mapper/Dao它⾥⾯的⽅法是映射l⽂件执⾏sql的接⼝所以没有实现不会⽤加@Service这个注解去解决。
解决⽅案:
1)@ Autowired改成@Resource注解
2)Mapper/Dao层的接⼝上加上@Repository注解
3)@Autowired写成@Autowired(required=false)
沈建宏required属性:
@Autowired(required=true):当使⽤@Autowired注解的时候,其实默认就@Autowired(required=true),表⽰注⼊的时候,该bean必须存在,否则就会注⼊失败。
@Autowired(required=false):表⽰忽略当前要注⼊的bean,如果有直接注⼊,没有跳过,不会报错。
雨的印记钢琴曲