Spring源码-Spring解决循环依赖
目录
- 前言
- 1、spring配置文件
- 2、入口
- 3、AbstractApplicationContext.refresh()
- 4、AbstractApplicationContext.finishBeanFactoryInitialization(beanFactory)
- 5、DefaultListableBeanFactory.preInstantiateSingletons();
- 6、AbstractBeanFactory.getBean();
- 7、 AbstractBeanFactory.getSingleton(beanName)
- 8、AbstractBeanFactory.getSingleton(beanName,singletonFactory);
- 9、AbstractAutowireCapableBeanFactory.createBean()
- 10、AbstractAutowireCapableBeanFactory.doCreateBean()
- 11、AbstractAutowireCapableBeanFactory.addSingletonFactory
- 12、AbstractAutowireCapableBeanFactory.populateBean
- 13、AbstractAutowireCapableBeanFactory.applyPropertyValues()
- 14、BeanDefinitionValueResolver.resolveValueIfNecessary
- 15、BeanDefinitionValueResolver.resolveReference
前言
为什么spring中要使用3级缓存?
现在有两个对象要创建,a和b,其中a是要被代理的(比如我们环绕通知对所有的service进行代理)
1、在不存在循环依赖的时候,
a在initializeBean()方法阶段在后置处理器的postProcessAfterBeanInitialization方法中被代理,a的生命周期就结束了。2、在存在循环依赖的时候,比如a依赖b,b依赖a,a在填充属性时发现了b,那么从spring中获取b,
在获取b后,填充b的属性时发现了a,那么b要从spring中获取a,但是a是要被代理的,怎么办?
这时候三级代理就来了,在a实例化完成后,会放入一个map中,key是beanName,value是一个lombda表达式,在这个表达式中是使用后置处理器对a进行代理,
那么b从spring中获取a的时候就会调用这个lombda表达式,对a进行代理,然后获取到(代理后的a)填充到b的属性中。
这就是三级缓存存在的意义
1、spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd"><bean id="car" class="Car"><property name="passenger" ref="passenger"></property></bean><bean id= "passenger" class="Passenger"><property name="car" ref="car"></property></bean>
</beans>
2、入口
public class TestIoc {@Testpublic void test() throws ClassNotFoundException, IOException {ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");Car bean = context.getBean(Car.class);Passenger passenger = bean.getPassenger();System.out.println(passenger);}
}
3、AbstractApplicationContext.refresh()
public void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {// Prepare this context for refreshing.prepareRefresh();// Tell the subclass to refresh the internal bean factory.//得到DefaultListableBeanFactoryConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();// Prepare the bean factory for use in this context.prepareBeanFactory(beanFactory);try {// Allows post-processing of the bean factory in context subclasses.// 子类继承当前类AbstractApplicationContext,重写postProcessBeanFactory方法//模板设计模式postProcessBeanFactory(beanFactory);// Invoke factory processors registered as beans in the context.invokeBeanFactoryPostProcessors(beanFactory);// Register bean processors that intercept bean creation.registerBeanPostProcessors(beanFactory);// Initialize message source for this context.initMessageSource();// Initialize event multicaster for this context.initApplicationEventMulticaster();// Initialize other special beans in specific context subclasses.onRefresh();// Check for listener beans and register them.registerListeners();// Instantiate all remaining (non-lazy-init) singletons.// 真正开始创建bean(解决循环依赖)//AbstractApplicationContext.finishBeanFactoryInitialization(beanFactory)finishBeanFactoryInitialization(beanFactory);// Last step: publish corresponding event.finishRefresh();}catch (BeansException ex) {if (logger.isWarnEnabled()) {logger.warn("Exception encountered during context initialization - " +"cancelling refresh attempt: " + ex);}// Destroy already created singletons to avoid dangling resources.destroyBeans();// Reset 'active' flag.cancelRefresh(ex);// Propagate exception to caller.throw ex;}finally {// Reset common introspection caches in Spring's core, since we// might not ever need metadata for singleton beans anymore...resetCommonCaches();}}}
4、AbstractApplicationContext.finishBeanFactoryInitialization(beanFactory)
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {// Initialize conversion service for this context.if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {beanFactory.setConversionService(beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));}// Register a default embedded value resolver if no bean post-processor// (such as a PropertyPlaceholderConfigurer bean) registered any before:// at this point, primarily for resolution in annotation attribute values.if (!beanFactory.hasEmbeddedValueResolver()) {beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));}// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);for (String weaverAwareName : weaverAwareNames) {getBean(weaverAwareName);}// Stop using the temporary ClassLoader for type matching.beanFactory.setTempClassLoader(null);// Allow for caching all bean definition metadata, not expecting further changes.beanFactory.freezeConfiguration();// Instantiate all remaining (non-lazy-init) singletons.// 开始实例化单例bean(DefaultListableBeanFactory.preInstantiateSingletons())beanFactory.preInstantiateSingletons();}
5、DefaultListableBeanFactory.preInstantiateSingletons();
public void preInstantiateSingletons() throws BeansException {if (this.logger.isDebugEnabled()) {this.logger.debug("Pre-instantiating singletons in " + this);}// Iterate over a copy to allow for init methods which in turn register new bean definitions.// While this may not be part of the regular factory bootstrap, it does otherwise work fine.List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);// Trigger initialization of all non-lazy singleton beans...for (String beanName : beanNames) {RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {if (isFactoryBean(beanName)) {Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);if (bean instanceof FactoryBean) {final FactoryBean<?> factory = (FactoryBean<?>) bean;boolean isEagerInit;if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)((SmartFactoryBean<?>) factory)::isEagerInit,getAccessControlContext());}else {isEagerInit = (factory instanceof SmartFactoryBean &&((SmartFactoryBean<?>) factory).isEagerInit());}if (isEagerInit) {getBean(beanName);}}}else {// 第一次进来 AbstractBeanFactory.getBean();getBean(beanName);}}}..............................................}
6、AbstractBeanFactory.getBean();
public Object getBean(String name) throws BeansException {return doGetBean(name, null, null, false);
}
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;// Eagerly check singleton cache for manually registered singletons.// 第一次,singletonObjects里获取不到,sharedInstance为nullObject sharedInstance = getSingleton(beanName);if (sharedInstance != null && args == null) {if (logger.isDebugEnabled()) {if (isSingletonCurrentlyInCreation(beanName)) {logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +"' that is not fully initialized yet - a consequence of a circular reference");}else {logger.debug("Returning cached instance of singleton bean '" + beanName + "'");}}bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);}else {.....................................................................if (mbd.isSingleton()) {// 首次进入sharedInstance = getSingleton(beanName, () -> {try {// AbstractAutowireCapableBeanFactory.createBean()return createBean(beanName, mbd, args);}catch (BeansException ex) {// Explicitly remove instance from singleton cache: It might have been put there// eagerly by the creation process, to allow for circular reference resolution.// Also remove any beans that received a temporary reference to the bean.destroySingleton(beanName);throw ex;}});bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);}.................................................................}return (T) bean;}
7、 AbstractBeanFactory.getSingleton(beanName)
protected Object getSingleton(String beanName, boolean allowEarlyReference) {Object singletonObject = this.singletonObjects.get(beanName);// 第一次进来为falseif (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {synchronized (this.singletonObjects) {// 一级缓存singletonObject = this.earlySingletonObjects.get(beanName);// 第二次进来满足条件if (singletonObject == null && allowEarlyReference) {// AOP处理过的对象ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);// bean创建完以后会放入singletonFactory中,这时还没有执行beanpostprocessor,也没有populateBean,当其他bean来获取时,会执行beanpostprocessor,然后放入early,防止后续获取时重复执行beanpostprocessor。并且放入二级缓存,从三级缓存里删除if (singletonFactory != null) {singletonObject = singletonFactory.getObject();this.earlySingletonObjects.put(beanName, singletonObject);this.singletonFactories.remove(beanName);}}}}return singletonObject;}
8、AbstractBeanFactory.getSingleton(beanName,singletonFactory);
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!)");}if (logger.isDebugEnabled()) {logger.debug("Creating shared instance of singleton bean '" + beanName + "'");}// 开始创建前放入singletonsCurrentlyInCreation中beforeSingletonCreation(beanName);boolean newSingleton = false;boolean recordSuppressedExceptions = (this.suppressedExceptions == null);if (recordSuppressedExceptions) {this.suppressedExceptions = new LinkedHashSet<>();}try {// 调用6.3中的ObjectFactory的lambod实现createBean()singletonObject = singletonFactory.getObject();newSingleton = true;}catch (IllegalStateException ex) {// Has the singleton object implicitly appeared in the meantime ->// if yes, proceed with it since the exception indicates that state.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;}// 创建结束后从singletonsCurrentlyInCreation中移除afterSingletonCreation(beanName);}if (newSingleton) {// bean已经创建完成,加入singletonObjects,从2级、3级中移除addSingleton(beanName, singletonObject);}}return singletonObject;}}
9、AbstractAutowireCapableBeanFactory.createBean()
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)throws BeanCreationException {...........................................................................try {// 第一次开始创建beanObject beanInstance = doCreateBean(beanName, mbdToUse, args);if (logger.isDebugEnabled()) {logger.debug("Finished creating instance of bean '" + beanName + "'");}return beanInstance;}..................................................}
10、AbstractAutowireCapableBeanFactory.doCreateBean()
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)throws BeanCreationException {// Instantiate the bean.BeanWrapper instanceWrapper = null;if (mbd.isSingleton()) {instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);}// 真正创建对象的方法(反射)if (instanceWrapper == null) {instanceWrapper = createBeanInstance(beanName, mbd, args);}................................................................// Eagerly cache singletons to be able to resolve circular references// even when triggered by lifecycle interfaces like BeanFactoryAware.boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&isSingletonCurrentlyInCreation(beanName));// TRUEif (earlySingletonExposure) {if (logger.isDebugEnabled()) {logger.debug("Eagerly caching bean '" + beanName +"' to allow for resolving potential circular references");}// 一个类首先被加入第三级缓存addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));}// Initialize the bean instance.Object exposedObject = bean;try {// 填充BeanpopulateBean(beanName, mbd, instanceWrapper);// 调用Bean实现的各种Aware接口方法exposedObject = initializeBean(beanName, exposedObject, mbd);}
...............................................................................return exposedObject;}
11、AbstractAutowireCapableBeanFactory.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);}}}
12、AbstractAutowireCapableBeanFactory.populateBean
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {................................................// 填充属性(解决循环依赖)if (pvs != null) {applyPropertyValues(beanName, mbd, bw, pvs);}}
13、AbstractAutowireCapableBeanFactory.applyPropertyValues()
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {if (pvs.isEmpty()) {return;}MutablePropertyValues mpvs = null;List<PropertyValue> original;if (pvs instanceof MutablePropertyValues) {mpvs = (MutablePropertyValues) pvs;if (mpvs.isConverted()) {// Shortcut: use the pre-converted values as-is.try {bw.setPropertyValues(mpvs);return;}catch (BeansException ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Error setting property values", ex);}}// 可能有多个依赖original = mpvs.getPropertyValueList();}else {original = Arrays.asList(pvs.getPropertyValues());}TypeConverter converter = getCustomTypeConverter();if (converter == null) {converter = bw;}BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);// Create a deep copy, resolving any references for values.List<PropertyValue> deepCopy = new ArrayList<>(original.size());boolean resolveNecessary = false;// 可能有多个依赖for (PropertyValue pv : original) {if (pv.isConverted()) {deepCopy.add(pv);}else {String propertyName = pv.getName();Object originalValue = pv.getValue();// 这里填充依赖的bean(里面又开始调用beanfactory.getBean方法)Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);Object convertedValue = resolvedValue;.......................................}
14、BeanDefinitionValueResolver.resolveValueIfNecessary
public Object resolveValueIfNecessary(Object argName, @Nullable Object value) {// We must check each value to see whether it requires a runtime reference// to another bean to be resolved.if (value instanceof RuntimeBeanReference) {RuntimeBeanReference ref = (RuntimeBeanReference) value;return resolveReference(argName, ref);}............................................................
}
15、BeanDefinitionValueResolver.resolveReference
private Object resolveReference(Object argName, RuntimeBeanReference ref) {try {Object bean;String refName = ref.getBeanName();refName = String.valueOf(doEvaluate(refName));if (ref.isToParent()) {if (this.beanFactory.getParentBeanFactory() == null) {throw new BeanCreationException(this.beanDefinition.getResourceDescription(), this.beanName,"Can't resolve reference to bean '" + refName +"' in parent factory: no parent factory available");}bean = this.beanFactory.getParentBeanFactory().getBean(refName);}else {// 这里又开始调用getBean(上面6)bean = this.beanFactory.getBean(refName);this.beanFactory.registerDependentBean(refName, this.beanName);}if (bean instanceof NullBean) {bean = null;}return bean;}catch (BeansException ex) {throw new BeanCreationException(this.beanDefinition.getResourceDescription(), this.beanName,"Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);}}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
