SpringBoot项目意外出现 循环依赖和注入的对象意外是Null的问题 Requested bean is currently in creation: Is there an unresolvable circular reference? 或 nested exception is java.lang.NullPointerException

1.Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mybatisPlusConfig': Invocation of init method failed; nested exception is java.lang.NullPointerException

2.Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'sqlSessionFactory': Requested bean is currently in creation: Is there an unresolvable circular reference?

 

以上2个情况均是指 迫切的注入依赖 导致

 

出现上面2种情况,无非就是启动时通过注入的Mapper或Service对象去初始化数据;前提是项目是真的没有循环依赖的情况下..

 

我这边的情况是 @Service接口和使用均没有手动声明循环依赖;排查了半天,只能妥协了;从代码里没有找到循环依赖的地方,想来可能是CGlib和JDK代理的时候导致的问题吧

 

通过 setMethod进行注入依然失败:Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'sqlSessionFactory': Requested bean is currently in creation: Is there an unresolvable circular reference?

@Autowired
public void setSysDatabaseService(ISysDatabaseService sysDatabaseService)

 

 

第一种解决方法就是:使用以下语句在项目启动后进行初始化数据,执行的时机可以通过 org.springframework.boot.SpringApplication#run(java.lang.String...)  看到

 

 

 @Bean
//    public ApplicationRunner initIgnoreTenantTables(ISysDatabaseTenantService sysDatabaseTenantService){
//        return args -> {
//            // 启动时初始化无租户的列表
//            List<String> notTenantTableNameList = sysDatabaseTenantService.findAllNotTenantTable().stream().map(SysDatabaseTenant::getTableName).collect(Collectors.toList());
//            ignoreTenantTables.addAll(notTenantTableNameList);
//        };
//    }

 

 

经实验,加 @Lazy注解无法应用到这个场景里;无法有效的解决此问题

 

 

我出现这个问题的位置是:

@Configuration
// @Configuration(proxyBeanMethods = false)
class AConfig {


  // Service是正常的结构,没有任何问题;在Controller层调用均没有问题;出现这个的原因,可能就是 急切 加载导致的

    private XXXService xxxService;


    @PostConstruct    // 无效
    public void init(){
          xxxService.myMethod1();
    }


    @Autowired  
    @Lazy
    public void setXXXService(){   // 无效
        xxxService.myMethod1();
    }


 @Bean     // 有效
  public ApplicationRunner initIgnoreTenantTables(ISysDatabaseTenantService sysDatabaseTenantService){
        return args -> {
           xxxService.myMethod1();
        };
    }


}

抛异常的位置:

org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement#inject

 

 org.springframework.beans.factory.support.DefaultListableBeanFactory#resolveDependency    ;这里进行抛异常的,具体位置忘了,有大能知道原因,麻烦告知下

 

posted @ 2021-07-30 15:48  星小梦  阅读(2417)  评论(0编辑  收藏  举报