Spring getBean(beanName)流程

  • Post author:
  • Post category:其他


在这里插入图片描述

在这里插入图片描述

上节分析到refresh()方法中finishBeanFactoryInitialization(beanFactory)中beanFactory.preInstantiateSingletons();循环所有的beanNames,调用getBean(beanName)


先学习一个方法:

    public static void AAA(ObjectFactory<?> objectFactory){
         objectFactory.getObject(); //调用getObject()方法实际调用的是BBB()方法
       }
     public static  Object BBB(String a){
        System.out.println(a);
          return "666";
 }
 public static void main(String[] args) {
     AAA(()->BBB("abc"));
 }


日志:

abc
  `genBean(beanName)主讲两个方法:`




一、Object sharedInstance = getSingleton(beanName);

	protected Object getSingleton(String beanName, boolean allowEarlyReference) {
	    //一级缓存取
		Object singletonObject = this.singletonObjects.get(beanName);
		if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
		//二级缓存取
			singletonObject = this.earlySingletonObjects.get(beanName);
			if (singletonObject == null && allowEarlyReference) {
				synchronized (this.singletonObjects) {
					singletonObject = this.singletonObjects.get(beanName);
					if (singletonObject == null) {
						singletonObject = this.earlySingletonObjects.get(beanName);
						if (singletonObject == null) {
						//三级缓存获取
							ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
							if (singletonFactory != null) {
							//此处调用getObject()方法,实际调用的是doCreateBean()中addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)) 中的getEarlyBeanReference(beanName, mbd, bean)方法,这个方法执行过切面了,生成了未注入属性,为初始化的半成品bean,并放入二级缓存
								singletonObject = singletonFactory.getObject();
								this.earlySingletonObjects.put(beanName, singletonObject);
								this.singletonFactories.remove(beanName);
							}
						}
					}
				}
			}
		}
		return singletonObject;
	}




二.createBean()

					//方法1 getSingleton()
					sharedInstance = getSingleton(beanName, () -> {
						try {
						//方法2 createBean()
							return createBean(beanName, mbd, args);
						}
						catch (BeansException ex) {
							destroySingleton(beanName);
							throw ex;
						}
					});


1.getSingleton()

   //下边代码只留主要的了
	public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
		synchronized (this.singletonObjects) {
		   //从一级缓存取
			Object singletonObject = this.singletonObjects.get(beanName);
			if (singletonObject == null) {
			 //加入到 正在创建Bean的集合(Set<String> singletonsCurrentlyInCreation)
				beforeSingletonCreation(beanName);
				try {
				   //此处执行getObject()方法,实际执行的是createBean(beanName, mbd, args)方法
					singletonObject = singletonFactory.getObject();
					newSingleton = true;
				}
				catch (IllegalStateException ex) {
				}
				catch (BeanCreationException ex) {
				}
				finally {
			//从正在创建Bean的集合(Set<String> singletonsCurrentlyInCreation)移除
					afterSingletonCreation(beanName);
				}
				if (newSingleton) {
				   //1.加入一级缓存
				   //2.从二级缓存移除
				   //1.从三级缓存移除
				   //1.加入registeredSingletons集合中
					addSingleton(beanName, singletonObject);
				}
			}
			return singletonObject;
		}
	}


2.doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)

 protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @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);
 	}
 	Object bean = instanceWrapper.getWrappedInstance();
 	Class<?> beanType = instanceWrapper.getWrappedClass();
 	if (beanType != NullBean.class) {
 		mbd.resolvedTargetType = beanType;
 	}
     //此处加入三级缓存,<beanName,ObjectFactory>,是不完整的bean,提前曝光防止循环依赖
     //如果没有aop等,可以不用三级缓存,如果有aop需要三级缓存,因为getEarlyBeanReference()方法执行了前后置处理器,是代理bean。
 	boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
 			isSingletonCurrentlyInCreation(beanName));
 	if (earlySingletonExposure) {
 		addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
 	}

 	// Initialize the bean instance.
 	Object exposedObject = bean;
 	try {
 	   //注入bean的属性
 		populateBean(beanName, mbd, instanceWrapper);
 		//初始化bean,初始化前后执行后置处理器
 		exposedObject = initializeBean(beanName, exposedObject, mbd);
 	}
 	catch (Throwable ex) {
 	}
 	try {
 		registerDisposableBeanIfNecessary(beanName, bean, mbd);
 	}
 	catch (BeanDefinitionValidationException ex) {
 	}
 	return exposedObject;
 }


2-1 addSingletonFactory() 把objectFactory加入三级缓存

 protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
 	synchronized (this.singletonObjects) {
 		if (!this.singletonObjects.containsKey(beanName)) {
 	    	//放入三级缓存
 			this.singletonFactories.put(beanName, singletonFactory);
 			this.earlySingletonObjects.remove(beanName);
 			this.registeredSingletons.add(beanName);
 		}
 	}
 }


2-2 populateBean(beanName, mbd, instanceWrapper)

注入bean的属性,各种类型的属性注入,list,map,bean等,一步步跟进
populateBean(beanName, mbd, instanceWrapper)-->
applyPropertyValues(beanName, mbd, bw, pvs)-->
valueResolver.resolveValueIfNecessary(pv, originalValue) 
//各种类型的属性注入,list,map,bean等
 public Object resolveValueIfNecessary(Object argName, @Nullable Object value) {
    //如果注入的是bean A,会去getBean(A)
 	if (value instanceof RuntimeBeanReference) {
 		RuntimeBeanReference ref = (RuntimeBeanReference) value;
 		return resolveReference(argName, ref);
 	}
 	else if (value instanceof RuntimeBeanNameReference) {
 		String refName = ((RuntimeBeanNameReference) value).getBeanName();
 		refName = String.valueOf(doEvaluate(refName));
 		if (!this.beanFactory.containsBean(refName)) {
 			throw new BeanDefinitionStoreException(
 					"Invalid bean name '" + refName + "' in bean reference for " + argName);
 		}
 		return refName;
 	}
 	else if (value instanceof BeanDefinitionHolder) {
 		// Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases.
 		BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
 		return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
 	}
 	else if (value instanceof BeanDefinition) {
 		// Resolve plain BeanDefinition, without contained name: use dummy name.
 		BeanDefinition bd = (BeanDefinition) value;
 		String innerBeanName = "(inner bean)" + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR +
 				ObjectUtils.getIdentityHexString(bd);
 		return resolveInnerBean(argName, innerBeanName, bd);
 	}
 	else if (value instanceof DependencyDescriptor) {
 		Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
 		Object result = this.beanFactory.resolveDependency(
 				(DependencyDescriptor) value, this.beanName, autowiredBeanNames, this.typeConverter);
 		for (String autowiredBeanName : autowiredBeanNames) {
 			if (this.beanFactory.containsBean(autowiredBeanName)) {
 				this.beanFactory.registerDependentBean(autowiredBeanName, this.beanName);
 			}
 		}
 		return result;
 	}
 	else if (value instanceof ManagedArray) {
 		// May need to resolve contained runtime references.
 		ManagedArray array = (ManagedArray) value;
 		Class<?> elementType = array.resolvedElementType;
 		if (elementType == null) {
 			String elementTypeName = array.getElementTypeName();
 			if (StringUtils.hasText(elementTypeName)) {
 				try {
 					elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader());
 					array.resolvedElementType = elementType;
 				}
 				catch (Throwable ex) {
 					// Improve the message by showing the context.
 					throw new BeanCreationException(
 							this.beanDefinition.getResourceDescription(), this.beanName,
 							"Error resolving array type for " + argName, ex);
 				}
 			}
 			else {
 				elementType = Object.class;
 			}
 		}
 		return resolveManagedArray(argName, (List<?>) value, elementType);
 	}
 	else if (value instanceof ManagedList) {
 		// May need to resolve contained runtime references.
 		return resolveManagedList(argName, (List<?>) value);
 	}
 	else if (value instanceof ManagedSet) {
 		// May need to resolve contained runtime references.
 		return resolveManagedSet(argName, (Set<?>) value);
 	}
 	else if (value instanceof ManagedMap) {
 		// May need to resolve contained runtime references.
 		return resolveManagedMap(argName, (Map<?, ?>) value);
 	}
 	else if (value instanceof ManagedProperties) {
 		Properties original = (Properties) value;
 		Properties copy = new Properties();
 		original.forEach((propKey, propValue) -> {
 			if (propKey instanceof TypedStringValue) {
 				propKey = evaluate((TypedStringValue) propKey);
 			}
 			if (propValue instanceof TypedStringValue) {
 				propValue = evaluate((TypedStringValue) propValue);
 			}
 			if (propKey == null || propValue == null) {
 				throw new BeanCreationException(
 						this.beanDefinition.getResourceDescription(), this.beanName,
 						"Error converting Properties key/value pair for " + argName + ": resolved to null");
 			}
 			copy.put(propKey, propValue);
 		});
 		return copy;
 	}
 	else if (value instanceof TypedStringValue) {
 		// Convert value to target type here.
 		TypedStringValue typedStringValue = (TypedStringValue) value;
 		Object valueObject = evaluate(typedStringValue);
 		try {
 			Class<?> resolvedTargetType = resolveTargetType(typedStringValue);
 			if (resolvedTargetType != null) {
 				return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
 			}
 			else {
 				return valueObject;
 			}
 		}
 		catch (Throwable ex) {
 			// Improve the message by showing the context.
 			throw new BeanCreationException(
 					this.beanDefinition.getResourceDescription(), this.beanName,
 					"Error converting typed String value for " + argName, ex);
 		}
 	}
 	else if (value instanceof NullBean) {
 		return null;
 	}
 	else {
 		return evaluate(value);
 	}
 }


简单分析一下方法resolveReference(argName, ref)

 private Object resolveReference(Object argName, RuntimeBeanReference ref) {
 	try {
 		Object bean;
 		Class<?> beanType = ref.getBeanType();
 		if (ref.isToParent()) {
 			BeanFactory parent = this.beanFactory.getParentBeanFactory();
 			if (parent == null) {
 			}
 			if (beanType != null) {
 				bean = parent.getBean(beanType);
 			}
 			else {
 				bean = parent.getBean(String.valueOf(doEvaluate(ref.getBeanName())));
 			}
 		}
 		else {
 			String resolvedName;
 			if (beanType != null) {
 				NamedBeanHolder<?> namedBean = this.beanFactory.resolveNamedBean(beanType);
 				bean = namedBean.getBeanInstance();
 				resolvedName = namedBean.getBeanName();
 			}
 			else {
 				resolvedName = String.valueOf(doEvaluate(ref.getBeanName()));
 				//这里geanBean()
 				bean = this.beanFactory.getBean(resolvedName);
 			}
 			this.beanFactory.registerDependentBean(resolvedName, this.beanName);
 		}
 		if (bean instanceof NullBean) {
 			bean = null;
 		}
 		return bean;
 	}
 	catch (BeansException ex) {
 }


2-3 initializeBean(beanName, exposedObject, mbd)初始化bean

    这里会执行实现了aware接口的类,和BeanPostProcessor 初始化前后执行后置处理器
 protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
 	if (System.getSecurityManager() != null) {
 		AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
 			invokeAwareMethods(beanName, bean);
 			return null;
 		}, getAccessControlContext());
 	}
 	else {
 	   //调用实现了BeanNameAware,BeanClassLoaderAware,BeanFactoryAware等接口的方法
 	   //下面有分析
 		invokeAwareMethods(beanName, bean);
 	}
 	Object wrappedBean = bean;
 	if (mbd == null || !mbd.isSynthetic()) {
 	//执行后置处理器
 		wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
 	}
 	try {
 	   //下面有分析
 		invokeInitMethods(beanName, wrappedBean, mbd);
 	}
 	catch (Throwable ex) {
 	}
 	if (mbd == null || !mbd.isSynthetic()) {
 			//执行后置处理器
 		wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
 	}
 	return wrappedBean;
 }


简单解析一下invokeAwareMethods(String beanName, Object bean)

	private void invokeAwareMethods(String beanName, Object bean) {
 	if (bean instanceof Aware) {
 		if (bean instanceof BeanNameAware) {
 			((BeanNameAware) bean).setBeanName(beanName);
 		}
 		if (bean instanceof BeanClassLoaderAware) {
 			ClassLoader bcl = getBeanClassLoader();
 			if (bcl != null) {
 				((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
 			}
 		}
 		if (bean instanceof BeanFactoryAware) {
 			((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
 		}
 	}
 }


简单解析一下invokeInitMethods(beanName, wrappedBean, mbd);

 	protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
 		throws Throwable {
    // 首先会检查是否是 InitializingBean ,如果是的话需要调用 afterPropertiesSet()
 	boolean isInitializingBean = (bean instanceof InitializingBean);
 	if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
 		if (logger.isTraceEnabled()) {
 			logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
 		}
 		if (System.getSecurityManager() != null) {
 			try {
 				AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
 				   //调用实现InitializingBean接口的afterPropertiesSet()方法
 					((InitializingBean) bean).afterPropertiesSet();
 					return null;
 				}, getAccessControlContext());
 			}
 			catch (PrivilegedActionException pae) {
 				throw pae.getException();
 			}
 		}
 		else {
 		  //调用实现InitializingBean接口的afterPropertiesSet()方法
 			((InitializingBean) bean).afterPropertiesSet();
 		}
 	}
 	if (mbd != null && bean.getClass() != NullBean.class) {
 	// 判断是否指定了 init-method(),
     // 如果指定了 init-method(),则再调用制定的init-method
 		String initMethodName = mbd.getInitMethodName();
 		if (StringUtils.hasLength(initMethodName) &&
 				!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
 				!mbd.isExternallyManagedInitMethod(initMethodName)) {
 				// 激活用户自定义的初始化方法
                 // 利用反射机制执行
 			invokeCustomInitMethod(beanName, bean, mbd);
 		}
 	}
 }
先调用afterPropertiesSet()方法,后反射init-method方法
//Spring 在完成实例化后,设置完所有属性,进行 “Aware 接口” 和 “BeanPostProcessor 前置处理”之后,会接着检测当前 bean 对象是否实现了 InitializingBean 接口。如果是,则会调用其 #afterPropertiesSet() 方法,进一步调整 bean 实例对象的状态。
  public interface InitializingBean {
     void afterPropertiesSet() throws Exception;
  }


示例

public class InitializingBeanTest implements InitializingBean {
 private String name;
 @Override
 public void afterPropertiesSet() throws Exception {
     System.out.println("InitializingBeanTest initializing...");
     this.name = "中路杀神";
 }
 public String getName() {
     return name;
 }
 public void setName(String name) {
     this.name = name;
 }
}


配置项如下

<bean id="initializingBeanTest" class="org.springframework.core.test.InitializingBeanTest">
 <property name="name" value="大西瓜"/>
</bean>


测试代码

InitializingBeanTest test = (InitializingBeanTest) factory.getBean("initializingBeanTest");
System.out.println("name :" + test.getName());


输出结果

InitializingBeanTest initializing...
中路杀神



版权声明:本文为itchenguang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。