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

女爷i 2024-03-30 08:44 158阅读 0赞

项目场景:SpringBoot+Mybatis。

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

1.注解没有添加:

controller:

  1. @RestController
  2. @AllArgsConstructor
  3. @RequestMapping("/enterprise")
  4. @Api(value = "企业数据", tags = "企业数据接口")
  5. public class EnterpriseController {
  6. private final IEnterpriseService service;
  7. }

注:

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

    @Autowired

    1. private final IEnterpriseService service;

service:

  1. @Service
  2. @AllArgsConstructor
  3. public class EnterpriseServiceImpl extends BaseServiceImpl<EnterpriseMapper, Enterprise> implements IEnterpriseService {
  4. public List<Map> countByType() {
  5. return baseMapper.countByType();
  6. }
  7. }

注:

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

    @Service
    public class EnterpriseServiceImpl extends BaseServiceImpl implements IEnterpriseService {

    1. @Autowired
    2. private final EnterpriseMapper mapper;
    3. @Autowired
    4. private final BlogMapper mapper;
    5. public List<Map> countByType() {
    6. return baseMapper.countByType();
    7. }

    }

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

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

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

  1. @EnableScheduling
  2. @SpringBootApplication
  3. @ComponentScan({"org.springblade","com.hello","com.test"})
  4. @MapperScan({"com.hello.**.mapper.**","com.test.**.mapper.**"})
  5. public class Application {
  6. public static void main(String[] args) {
  7. BladeApplication.run(CommonConstant.APPLICATION_NAME, Application.class, args);
  8. }
  9. }

注:

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

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

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

  1. @GetMapping("/count")
  2. public R<EnterpriseVO> test(@RequestBody Enterprise enterprise){
  3. EnterpriseVO detail = service.test(enterprise);
  4. return R.data(detail);
  5. }
  6. @PostMapping("/count")
  7. public R<Enterprise> update(@RequestBody Enterprise enterprise){
  8. boolean flag = service.updateByBody(enterprise);
  9. Enterprise entity = service.selectInfo(enterprise);
  10. return R.data(entity);
  11. }

异常排查技巧:

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

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

发表评论

表情:
评论列表 (有 0 条评论,158人围观)

还没有评论,来说两句吧...

相关阅读