关注“苏三说技术”,回复:开发手册、时间管理 有惊喜。web
也许有些朋友对spring的循环依赖问题并不了解,让咱们先一块儿看看这个例子。spring
@Service public class AService { private BService bService; public AService(BService bService) { this.bService = bService; } public void doA() { System.out.println("call doA"); } }
@Service public class BService { private AService aService; public BService(AService aService) { this.aService = aService; } public void doB() { System.out.println("call doB"); } }
@RequestMapping("/test") @RestController public class TestController { @Autowired private AService aService; @RequestMapping("/doSameThing") public String doSameThing() { aService.doA(); return "success"; } }
@SpringBootApplication public class Application { /** * 程序入口 * @param args 程序输入参数 */ public static void main(String[] args) { new SpringApplicationBuilder(Application.class).web(WebApplicationType.SERVLET).run(args); } }
咱们在运行Application类的main方法启动服务时,报了以下异常:缓存
Requested bean is currently in creation: Is there an unresolvable circular reference?
这里提示得很明显,出现了循环依赖。 app
什么是循环依赖? ide
循环依赖是实例a依赖于实例b,实例b又依赖于实例a。函数
或者实例a依赖于实例b,实例b依赖于实例c,实例c又依赖于实例a。ui
像这种多个实例之间的相互依赖关系构成一个环形,就是循环依赖。 this
为何会造成循环依赖?spa
上面的例子中AService实例化时会调用构造方法 public AService(BService bService),该构造方法依赖于BService的实例。此时BService尚未实例化,须要调用构造方法public BService(AService aService)才能完成实例化,该构造方法巧合又须要AService的实例做为参数。因为AService和BService都没有提早实例化,在实例化过程当中又相互依赖对方的实例做为参数,这样构成了一个死循环,因此最终都没法再实例化了。prototype
spring要如何解决循环依赖?
只须要将上面的例子稍微调整一下,不用构造函数注入,直接使用Autowired注入。
@Service public class AService { @Autowired private BService bService; public AService() { } public void doA() { System.out.println("call doA"); } }
@Service public class BService { @Autowired private AService aService; public BService() { } public void doB() { System.out.println("call doB"); } }
咱们看到能够正常启动了,说明循环依赖被本身解决了
spring为何能循环依赖?
调用applicationContext.getBean(xx)方法,最终会调到AbstractBeanFactory类的doGetBean方法。因为该方法很长,我把部分不相干的代码省略掉了。
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType, @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException { final String beanName = transformedBeanName(name); Object bean; Object sharedInstance = getSingleton(beanName); if (sharedInstance != null && args == null) { 省略........ bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { 省略........ if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, () -> { try { return createBean(beanName, mbd, args); } catch (BeansException ex) { destroySingleton(beanName); throw ex; } }); bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } else if (mbd.isPrototype()) { // It's a prototype -> create a new instance. Object prototypeInstance = null; try { beforePrototypeCreation(beanName); prototypeInstance = createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } else { String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); } try { Object scopedInstance = scope.get(beanName, () -> { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } }); bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; consider " + "defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex); } } } catch (BeansException ex) { cleanupAfterBeanCreationFailure(beanName); throw ex; } } 省略........ return (T) bean; }
咱们能够看到,该方法一进来会调用getSingleton方法从缓存获取实例,若是获取不到。会判断做用域是否为:单例,多列 或者 都不是,不一样的做用域建立实例的规则不同。接下来,咱们重点看一下getSingleton方法。
public Object getSingleton(String beanName) { return getSingleton(beanName, true); }
protected Object getSingleton(String beanName, boolean allowEarlyReference) { Object singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { synchronized (this.singletonObjects) { singletonObject = this.earlySingletonObjects.get(beanName); if (singletonObject == null && allowEarlyReference) { ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName); if (singletonFactory != null) { singletonObject = singletonFactory.getObject(); this.earlySingletonObjects.put(beanName, singletonObject); this.singletonFactories.remove(beanName); } } } } return singletonObject; }
咱们发现有三个Map集合:
/** Cache of singleton objects: bean name --> bean instance */ private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256); /** Cache of singleton factories: bean name --> ObjectFactory */ private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16); /** Cache of early singleton objects: bean name --> bean instance */ private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
singletonObjects对应一级缓存,earlySingletonObjects对应二级缓存,singletonFactories对应三级缓存。
上面getSingleton方法的逻辑是:
获取实例须要调用applicationContext.getBean("xxx")方法,第一次调用getBean方法,代码走到getSingleton方法时返回的singletonObject对象是空的。而后接着往下执行,默认状况下bean的做用域是单例的,接下来咱们重点看看这段代码:
createBean方法会调用doCreateBean方法,该方法一样比较长,咱们把不相干的代码省略掉。
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args) throws BeanCreationException { BeanWrapper instanceWrapper = null; 省略...... if (instanceWrapper == null) { instanceWrapper = createBeanInstance(beanName, mbd, args); } final Object bean = instanceWrapper.getWrappedInstance(); 省略........ boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); } Object exposedObject = bean; try { populateBean(beanName, mbd, instanceWrapper); exposedObject = initializeBean(beanName, exposedObject, mbd); } catch (Throwable ex) { 省略 ..... } 省略 ....... return exposedObject; }
该方法的主要流程是:
咱们关注的重点能够先放到addSingletonFactory方法上。
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) { Assert.notNull(singletonFactory, "Singleton factory must not be null"); synchronized (this.singletonObjects) { if (!this.singletonObjects.containsKey(beanName)) { this.singletonFactories.put(beanName, singletonFactory); this.earlySingletonObjects.remove(beanName); this.registeredSingletons.add(beanName); } } }
该方法的逻辑是判断若是singletonObjects(一级缓存)中找不到实例,则将singletonFactory实例放到singletonFactories(三级缓存)中,而且移除earlySingletonObjects(二级缓存)中的实例。
createBean方法执行完以后,会调用外层的getSingleton方法
咱们重点看看这个getSingleton方法
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) { Assert.notNull(beanName, "Bean name must not be null"); synchronized (this.singletonObjects) { Object singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null) { if (this.singletonsCurrentlyInDestruction) { throw new BeanCreationNotAllowedException(beanName, "Singleton bean creation not allowed while singletons of this factory are in destruction " + "(Do not request a bean from a BeanFactory in a destroy method implementation!)"); } beforeSingletonCreation(beanName); boolean newSingleton = false; boolean recordSuppressedExceptions = (this.suppressedExceptions == null); if (recordSuppressedExceptions) { this.suppressedExceptions = new LinkedHashSet<>(); } try { singletonObject = singletonFactory.getObject(); newSingleton = true; } catch (IllegalStateException ex) { singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null) { throw ex; } } catch (BeanCreationException ex) { if (recordSuppressedExceptions) { for (Exception suppressedException : this.suppressedExceptions) { ex.addRelatedCause(suppressedException); } } throw ex; } finally { if (recordSuppressedExceptions) { this.suppressedExceptions = null; } afterSingletonCreation(beanName); } if (newSingleton) { addSingleton(beanName, singletonObject); } } return singletonObject; } }
该方法逻辑很简单,就是先从singletonObjects(一级缓存)中获取实例,若是获取不到,则调用singletonFactory.getObject()方法建立一个实例,而后调用addSingleton方法放入singletonObjects缓存中。
protected void addSingleton(String beanName, Object singletonObject) { synchronized (this.singletonObjects) { this.singletonObjects.put(beanName, singletonObject); this.singletonFactories.remove(beanName); this.earlySingletonObjects.remove(beanName); this.registeredSingletons.add(beanName); } }
该方法会将实例放入singletonObjects(一级缓存),而且删除singletonFactories(二级缓存),这样之后再调用getBean时,都能从singletonObjects(一级缓存)中获取到实例了。
说了这么多,再回到示例中的场景。
spring为何要用三级缓存,而不是二级缓存?
像示例的这种状况只用二级缓存是没有问题的。
可是假若有这种状况:a实例同时依赖于b实例和c实例,b实例又依赖于a实例,c实例也依赖于a实例。
a实例化时,先提早暴露objectFactorya到三级缓存,调用getBean(b)依赖注入b实例。b实例化以后,提早暴露objectFactoryb到三级缓存,调用getBean(a)依赖注入a实例,因为提早暴露了objectFactorya,此时能够从三级缓存中获取到a实例, b实例完成了依赖注入,升级为一级缓存。a实例化再getBean(c)依赖注入c实例,c实例化以后,提早暴露objectFactoryc到三级缓存,调用getBean(a)依赖注入a实例,因为提早暴露了objectFactorya,此时能够从三级缓存中获取到a实例。注意这里又要从三级缓存中获取a实例,咱们知道三级缓存中的实例是经过调用singletonFactory.getObject()方法获取的,返回结果每次均可能不同。若是不用二级缓存,这里会有问题,两次获取的a实例不同。
总结:
只有单例的状况下才能解决循环依赖问题,而且allowCircularReferences要设置成true。
如下状况仍是会出现循环依赖:
你们喜欢这篇文章的话,烦请关注一下 :苏三说技术