如何判断循环依赖,并解决循环依赖案例

 在写项目过程中,发现项目报异常,一直不知道是什么原因?最后找到原因时循环依赖导致的!

循环依赖其实就是循环引用(circular reference),也就是两个或则两个以上的bean互相持有对方,最终形成闭环。比如A依赖于B,B依赖于C,C又依赖于A。如下图:

如何判断循环依赖,并解决循环依赖案例

下面是我在写代码时遇到的bug, 在遇到这类bug的时候我们首先检查看是否有“circular reference”这样的字样,然后再查看报错的信息中,我们明显会发现一个 “Unsatisfied dependency expressed through field xxx” , 这里的xxx代指造成循环依赖的字段,字段前面'com.leyou.auth.config.MvcConfig'表示该字段所在的这个类;因此找到这个类,在该字段上加上@Lazy进行懒加载就可以解决问题!

如何判断循环依赖,并解决循环依赖案例

代码中的日志记录

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'orderServiceImpl' defined in file [C:\Users\carlos\IdeaProjects\leyou\ly-trade\target\classes\com\leyou\trade\Service\impl\OrderServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.leyou.item.client.ItemClient': FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration': Unsatisfied dependency expressed through method 'setConfigurers' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.leyou.auth.config.MvcConfig': Unsatisfied dependency expressed through field 'jwtUtils'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.leyou.auth.config.AuthConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.leyou.auth.client.AuthClient': FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'mvcResourceUrlProvider': Requested bean is currently in creation: Is there an unresolvable circular reference?