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); } }
