解决Bean with name ‘XX‘ has been injected into other beans 问题

 

问题

话不多说,先上Error提示: 

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'StoreOrderFrontController': Unsatisfied dependency expressed through field 'orderService'; 
nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'XX: Bean with name 'orderServiceImpl' has been injected into other beans [pinkServiceImpl,combinationServiceImpl] 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:643)
	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130)

信息已经说的很明白。是因为循环引用导致的问题。

说下背景:项目里面多个人开发,刚开始为了赶进度,就怎么快怎么来?为什么这样呢?主要是几个原因:

1、人少(开发2-3人)

2、事多(需求大量积压)

3、人员流动性(不解释)。

4、其他的问题

开发就变动耦合性比较高了。问题找到了,解决问题就简单多了。

解决方案

两个方法:

1、解耦。把相关的引用方法进行拆分,然后再进行二次开发,搞定这个事情就可以了。

这个方法在忙的时候根本实现不了,那就用另外一个方法。

2、使用注解@Lazy

就是使用懒加载,不在刚开始初始化的时候就创建对应的Bean。这样就可以避免这个问题。

总结

在团队开发的项目中,循环依赖的问题一般很难在代码层面上进行规避。所以最好在引用其他service的时候,使用@Lazy注解可以很好的解决循环依赖的问题。

后记

多说一两句:Java的异常机制其实比较齐全。很多错误信息在debug模式下都会输出出来。

您解决问题的话,需要一点耐心再加上一点英语阅读水平就可以解决80%以上的问题。其他的大多数是IDE缓存等各种问题。