No qualifying bean of type或Unsatisfied dependency expressed through field ‘XXXService‘或@Autowired 注入

简介: No qualifying bean of type或Unsatisfied dependency expressed through field ‘XXXService‘或@Autowired 注入

这种类似的bean报错基本都是因为bean使用自动注入的时候没有成功注入,可以解决的方法有

1.对象没有被加载到容器

首先要看要加载的类上有没有对应的注解@Controller、@Service、@Mapper、@Repository、 @Component(一些工具类等可以加)、@Configuration

@Mapper和@Repository区别

  • @Mapper和@Repository都是用在dao层接口的上的注解
  • @Mapper可以单独加在dao层接口类上,使得该类直接加载。如果有多个mapper需要加载则可以启动类上配置@MapperScan
  • @Repository单独使用没有用,只是给该mapper接口作为标识,想要被加载到需要用@MapperScannerConfigurer扫描

2.对象没有被扫描到

如果对应的对象已经加上了对应的注解,但还是报错,则可能是因为启动类上没有加上@MapperScan或者@ComponentScan导致因此导致对象没有被扫描到,无法加载到容器中。没有加上的话在启动类加上即可

@MapperScan和@ComponentScan区别

  • 两个Scan不能同时使用,否则mapper会扫描不到,如果非要同时使用则需要@MapperScan(basePackages = {})使@MapperScan只扫描mapper包
  • @MapperScan只扫描Mapper接口的类
  • 而@ComponentScan会扫描@Controller、@Service、@Repository、@Component类等类装配到spring容器中

本次博主出错就是因为两个项目之间要调用service类但只使用了@MapperScan,因此无法进行加载,改成@ComponentScan即可,而@ComponentScan的话扫描的包记得范围需要大一点否则也会报错

3.注意包的层级

如果是测试类上进行测试的时候,要注意测试类的包层级和原先java包下的层级要对应上

4.对象不是由spring加载,而是new来创建

需要注入的对象通常是只需要声明而不需要创建,创建的工作是交给spring的IOC容器来操作,一般加上了static等的操作可能就是已经创建了

5.一个项目里有多个子项目,且每个子项目都有启动类的

注意:通常相同层级的子项目的启动类上扫描只能有一个@ComponentScan在扫描,有两个会发生冲突

 

目录
相关文章
|
7月前
|
XML 数据格式
解决Unsatisfied dependency expressed through field ‘jdbcTemplate‘;问题~
解决Unsatisfied dependency expressed through field ‘jdbcTemplate‘;问题~
166 0
|
2天前
No qualifying bean of type [com.XX.mapper.SysNameMapper ] found for dependency
No qualifying bean of type [com.XX.mapper.SysNameMapper ] found for dependency
75 0
|
2天前
Unsatisfied dependency expressed through field ‘baseMapper‘
Unsatisfied dependency expressed through field ‘baseMapper‘
21 2
|
7月前
|
Java 编译器
解决NoSuchBeanDefinitionException: No qualifying bean of type ‘bean.User‘ available
解决NoSuchBeanDefinitionException: No qualifying bean of type ‘bean.User‘ available
记一个SpringBoot中属性注入失败的问题Consider defining a bean of type ''' in your configuration...
记一个SpringBoot中属性注入失败的问题Consider defining a bean of type ''' in your configuration...
241 0
|
10月前
Error creating bean with name ‘userServiceImpl‘: Unsatisfied dependency expressed through field ‘bas
Error creating bean with name ‘userServiceImpl‘: Unsatisfied dependency expressed through field ‘bas
216 0
|
11月前
|
Java
springboot3 解决:Could not autowire. No beans of ‘JavaMailSender‘ type found
因为 spring-boot-starter-mail 默认使用某些包发生了变化,在 2.2.xx 版本前后不一,解决对应bug
293 0
|
Java Spring
Annotation-specified bean name ‘brdbService‘ for bean class
Annotation-specified bean name ‘brdbService‘ for bean class
212 0
记一个SpringBoot中属性注入失败的问题Consider defining a bean of type ''' in your configuration...
记一个SpringBoot中属性注入失败的问题Consider defining a bean of type ''' in your configuration...
152 0
SPRING02_核心注解、Bean、primary、DependsOn、Lazy、Scope、ComponentScan、详解Import、Lookup注解(五)
SPRING02_核心注解、Bean、primary、DependsOn、Lazy、Scope、ComponentScan、详解Import、Lookup注解(五)
117 0