异常:org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name

项目场景:SpringBoot+Mybatis。

出现这种异常主要是无法创建bean到容器中,主要有以下几种情况:

1.注解没有添加:

controller:

@RestController
@AllArgsConstructor
@RequestMapping("/enterprise")
@Api(value = "企业数据", tags = "企业数据接口")
public class EnterpriseController {
	private final IEnterpriseService service;
}

注:

  • controller类要加入@RestController注解,@AllArgsConstructor注解视情况而定。
  • 引入了private final IEnterpriseService service,所以需要注入,可以在controller类上加入@AllArgsConstrctor注解修饰。
  • 或者用@Autowired修饰注入变量。
    @Autowired
	private final IEnterpriseService service;

service:

@Service
@AllArgsConstructor
public class EnterpriseServiceImpl extends BaseServiceImpl<EnterpriseMapper, Enterprise> implements IEnterpriseService {
	
	public List<Map> countByType() {
		return baseMapper.countByType();
	}
}

注:

  • service层要加入@Service注解。
  • 如果service层中引入了Mapper变量,则需要加入@AllArgsConstrctor注解;当然也可以用@Autowired注解修饰变量。不过推荐使用@AllArgsConstrctor注解,因为只需要在类上引入一次;使用@Autowired注解需要修饰每一个引入的Mapper,极其繁琐。
@Service
public class EnterpriseServiceImpl extends BaseServiceImpl<EnterpriseMapper, Enterprise> implements IEnterpriseService {

    @Autowired
	private final EnterpriseMapper mapper;

    @Autowired
	private final BlogMapper mapper;

	public List<Map> countByType() {
		return baseMapper.countByType();
	}
}

2.接口有没有对应的实现类,以及实现类实现的接口是否正确。

3.项目中的文件是否重名,全局定位异常文件,并修改为不同文件名。

4.启动类中注解是否扫描到所有mapper。

@EnableScheduling
@SpringBootApplication
@ComponentScan({"org.springblade","com.hello","com.test"})
@MapperScan({"com.hello.**.mapper.**","com.test.**.mapper.**"})
public class Application {

	public static void main(String[] args) {
		BladeApplication.run(CommonConstant.APPLICATION_NAME, Application.class, args);

	}

}

注:

  • @ComponentScan注解和@MapperScan注解一定要扫描到所有文件路径,多个路径之间用逗号分隔开。
  • 或者在yml配置文件中配置mapper扫描路径。

5.Mapper.xml文件中配置的resultMap对应的实体类路径是否正确,以及各种Mybatis标签对应的resultMap或者resultType路径是否正确。

6.接口对应的地址是否重复。如下图,两个接口均使用了相同的地址,会出现异常。


	@GetMapping("/count")
	public R<EnterpriseVO> test(@RequestBody  Enterprise enterprise){
		EnterpriseVO detail = service.test(enterprise);
		return R.data(detail);
	}
	
	@PostMapping("/count")
	public R<Enterprise> update(@RequestBody Enterprise enterprise){
		boolean flag = service.updateByBody(enterprise);
		Enterprise entity = service.selectInfo(enterprise);
		return R.data(entity);
	}

异常排查技巧:

通常出现这种异常会在控制台打印出一堆异常信息,在控制台上方的异常信息大多是和程序真正的问题没有直接关系的,这里给出以下异常排查技巧:

  1. 控制台看报错:从下往上看。
  2. 利用好idea的全局搜索定位功能去排查异常。

猜你喜欢

转载自blog.csdn.net/qq_44973310/article/details/128302144