记一次SpringBoot程序启动时因循环依赖的报错与解决

457 阅读1分钟

1、背景:

今天,写完一个功能后,打算跑起来试试,但是,在项目启动时失败了,查看控制台有报错,具体错误信息如下:

Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'taskManager': Bean with name 'taskManager' has been injected into other beans [taskServiceImpl] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.

2、原因:

我在taskServiceImpl中注入了一个bean,记作beanA,然而beanA中又注入了一个bean,记作beanB,其中beanB中注入了taskServiceImpl,这样就发生了循环依赖。其实我只想调用beanA的一个方法,结果发生了循环依赖。

3、解决:

3.1、拆分想用的方法到一个独立的类中

例如,将beanA中想用的那个方法放在一个新的类中,然后将原来调用该方法的地方指向调用新的bean

3.2、使用@Lazy注解

使用@Lazy注解延时加载其中一个bean,这样两边在真正使用时都可以初始化成功。但要注意,如果其中一个bean依赖的其它bean中还会反过来依赖这个bean,那么@Lazy注解适合加在这个bean上。