Spring循環引用踩坑記

項目啓動的時候報瞭如下的錯誤:

Error creating bean with name 'boingpayCallbackController': Unsatisfied dependency expressed through field 'transitToCashService'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'transitToCashService': Bean with name 'transitToCashService' has been injected into other beans [flowCheckCore,bankFlowCheckService,checkLogService] 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 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.
 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
 at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
 at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
 at org.springframework.beans.factory.support.DefaultLis

分析:

看了下報的是循環依賴的錯誤,但是Spring單例是支持循環依賴的,然後網上搜索發現是因爲transitToCashService這個類中的方法有加**@Async**註解(只需要類/方法有標註@Async註解的Bean最終都會生成一個代理對象重新賦值並add進Spring容器內)。

解決辦法:

​ 不要讓@Async的Bean參與循環依賴

​ 使用@Lazy或者@ComponentScan(lazyInit = true)

​ 通過後置處理器設置allowRawInjectionDespiteWrapping=true(@Aysnc方法將不起作用)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章