BeanCurrentlyInCreationException sqlSessionFactory Requested bean is currently in creation: Is there an unresolvable circular reference?

Springboot项目集成h2 databse遇到的异常

1.异常现象

Springboot集成h2 database,h2配置如下

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:~/test
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.schema=classpath:db/*.sql
spring.datasource.initialization-mode=always
spring.datasource.continue-on-error=false

spring.h2.console.path=/h2-console
spring.h2.console.enabled=true

当spring.datasource.schema配置脚本时,就会抛出异常,具体异常信息为:

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?

如果不配置spring.datasource.schema的值,也就不会初始化数据库脚本,也不会抛异常。

2.问题解决

由于能力不足,在网上到处搜索,搜索了整整一天终于解决了。这个异常的原因看名字就能大致猜出来:Bean对象当前正在创建异常。

由于公司用的RPC框架的注解的类都有这个异常抛出,普通@Service类都可以正常注入Bean。所以可以断定是公司RPC框架注解的问题,不能在Bean完全创建好后再注入导致的问题。

解决办法就是在注入的属性上添加@Lazy注解,表示暂时不注入对象,等到调用该属性(接口)时再注入Bean。类似下方代码

@公司RPC
@Service
public class UserService{

    @Lazy
    @Autowired
    private UserMapper userMapper;


    public User getById(String id){

         return userMapper.getById(id);
    }

}        
原文地址:https://www.cnblogs.com/hdwang/p/14186467.html