// 创建指定的bean
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
// 对于单例Bean,先从容器中缓存中获取同名Bean
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 创建实例对象
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
// 获取实例化对象的类型
Class> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
// 调用PostProcessor后置处理器
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
mbd.postProcessed = true;
}
}
// 向容器中缓存单例Bean对象,以防循环引用
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
// 为了防止循环引用,尽早持有对象的引用
addSingletonFactory(beanName, new ObjectFactory() {
@Override
public Object getObject() throws BeansException {
return getEarlyBeanReference(beanName, mbd, bean);
}
});
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
// 将Bean实例对象封装,并且对bean进行填充,将各个属性值注入。
// 如果存在依赖其他bean的属性,则递归初始依赖bean
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
// 初始化bean对象,比如init-method
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
if (earlySingletonExposure) {
// 获取指定名称的已注册的单例Bean对象
Object earlySingletonReference = getSingleton(beanName, false);
// 循环依赖的情况下,earlySingletonReference不为空
if (earlySingletonReference != null) {
// exposedObject没有在初始化方法中被改变,也就是没有被增强
if (exposedObject == bean) {
// 当前实例化的Bean初始化完成
exposedObject = earlySingletonReference;
}
// 当前Bean依赖其他Bean,并且当发生循环引用时不允许新创建实例对象
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set actualDependentBeans = new LinkedHashSet(dependentBeans.length);
// 获取当前Bean所依赖的其他Bean
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] 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.");
}
}
}
}
// 注册完成依赖注入的Bean
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
说明: ① 对于单例bean,先从factoryBeanInstanceCache缓存中移除beanName,返回BeanWrapper。 ② createBeanInstance方法:实例化bean,BeanDefinition转换BeanWrapper。 ③ 允许后处理修改合并BeanDefinition(譬如:autowired注解预解析)。 ④ 循环依赖的处理。 ⑤ 属性填充,将所有的属性填充到bean实例(populateBean方法) ⑥ registerDisposableBeanIfNecessary方法:注册DisposableBean,便于执行配置的destory-method。
说明: ① 解析Bean的class类,并将解析结果设置到BeanDefinition。 ② 如果工厂方法不为空则使用factory-method工厂方法初始化(instantiateUsingFactoryMethod方法)。 ③ 判断构造函数参数是否被初始化? ④ 如果构造函数参数已经初始化,那么使用带参数构造函数自动注入(调用autowireConstructor方法)。 ⑤ 否则使用无参构造函数自动注入(调用instantiateBean方法)。
说明: ① 使用postProcessAfterInstantiation方法控制程序是否继续进行属性填充。 ② 注入方式(byName / byType)获取依赖的bean,放入到PropertyValues。 ③ 使用postProcessPropertyValues方法对属性获取完毕填充前对属性的处理,譬如属性校验。 ④ 将所有PropertyValues中的属性填充至BeanWrapper中(applyPropertyValues)。 -----------------------bean名称方式注入 --- byName---------------------------
// IOC容器使用与Bean名称相匹配的属性类注入;autowire="byName"
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
// 查找BeanWrapper中需要依赖注入的属性
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
// 遍历属性名称
for (String propertyName : propertyNames) {
// 查找属性名称是否存在于singletonObjects或者beanDefinitionMap
// 如果没找到判断parentBeanFactory是否存在属性名称
if (containsBean(propertyName)) {
// 递归初始化依赖的bean
Object bean = getBean(propertyName);
// 将初始化的bean,添加到pvs
pvs.add(propertyName, bean);
// 注册依赖
registerDependentBean(propertyName, beanName);
if (logger.isDebugEnabled()) {
logger.debug("Added autowiring by name from bean name '" + beanName +
"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
}
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
"' by name: no matching bean found");
}
}
}
}
说明: ① 获取BeanDefinition中PropertyValues属性名称数组。 ② 遍历属性名称数组,将这些属性Bean添加到入参pvs(MutablePropertyValues)中。 ③ 分别将依赖的属性Bean进行注册。 -----------------------bean类型方式注入 --- byType---------------------------
// 根据Bean类型自动装配注入
protected void autowireByType(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
// 获取类型转换器
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
Set autowiredBeanNames = new LinkedHashSet(4);
// 查找BeanWrapper中需要依赖注入的属性
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
try {
// 获取属性描述对象
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
// 如果属性类型不等于Object类型
if (!Object.class.equals(pd.getPropertyType())) {
// 获取属性的setter方法
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
// Do not allow eager init for type matching in case of a prioritized post-processor.
boolean eager = !PriorityOrdered.class.isAssignableFrom(bw.getWrappedClass());
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
// 解析指定beanName的属性所匹配的值,并把解析到的属性名称存储在autowiredBeanNames中
// 当属性存在多个封装bean时,将都会注入
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
if (autowiredArgument != null) {
// 将属性Bean添加到入参pvs(MutablePropertyValues)
pvs.add(propertyName, autowiredArgument);
}
// 遍历自动注入的beanName
for (String autowiredBeanName : autowiredBeanNames) {
// 注册依赖
registerDependentBean(autowiredBeanName, beanName);
if (logger.isDebugEnabled()) {
logger.debug("Autowiring by type from bean name '" + beanName + "' via property '" +
propertyName + "' to bean named '" + autowiredBeanName + "'");
}
}
// 清空当前的集合容器
autowiredBeanNames.clear();
}
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
}
}
}
说明: ① 获取BeanDefinition中PropertyValues属性名称数组。 ② 解析beanName属性所匹配的值,并把解析到的属性名称存储在autowiredBeanNames中(包括集合类型)。 ③ 将属性Bean添加到入参pvs(MutablePropertyValues) ④ 注册依赖
@Override
public void setPropertyValues(PropertyValues pvs) throws BeansException {
setPropertyValues(pvs, false, false);
}
@Override
public void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown, boolean ignoreInvalid)
throws BeansException {
List propertyAccessExceptions = null;
// 获取PropertyValue类型List
List propertyValues = (pvs instanceof MutablePropertyValues ?
((MutablePropertyValues) pvs).getPropertyValueList() : Arrays.asList(pvs.getPropertyValues()));
// 遍历propertyValues
for (PropertyValue pv : propertyValues) {
try {
// 设置PropertyValue
setPropertyValue(pv);
}
catch (NotWritablePropertyException ex) {
if (!ignoreUnknown) {
throw ex;
}
// Otherwise, just ignore it and continue...
}
catch (NullValueInNestedPathException ex) {
if (!ignoreInvalid) {
throw ex;
}
// Otherwise, just ignore it and continue...
}
catch (PropertyAccessException ex) {
if (propertyAccessExceptions == null) {
propertyAccessExceptions = new LinkedList();
}
propertyAccessExceptions.add(ex);
}
}
// If we encountered individual exceptions, throw the composite exception.
if (propertyAccessExceptions != null) {
PropertyAccessException[] paeArray =
propertyAccessExceptions.toArray(new PropertyAccessException[propertyAccessExceptions.size()]);
throw new PropertyBatchUpdateException(paeArray);
}
}
@Override
public void setPropertyValue(PropertyValue pv) throws BeansException {
PropertyTokenHolder tokens = (PropertyTokenHolder) pv.resolvedTokens;
if (tokens == null) {
String propertyName = pv.getName();
BeanWrapperImpl nestedBw;
try {
// 通过给定的属性名称获取BeanWrapper
nestedBw = getBeanWrapperForPropertyPath(propertyName);
}
catch (NotReadablePropertyException ex) {
throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
"Nested property in path '" + propertyName + "' does not exist", ex);
}
// 解析给定属性名称为PropertyTokenHolder
tokens = getPropertyNameTokens(getFinalPath(nestedBw, propertyName));
if (nestedBw == this) {
pv.getOriginalPropertyValue().resolvedTokens = tokens;
}
// 真正设置属性值
nestedBw.setPropertyValue(tokens, pv);
}
else {
setPropertyValue(tokens, pv);
}
}
说明: ① 将PropertyValues转换为List对象。 ② 遍历集合List。 ③ resolveValueIfNecessary方法将属性引用转换为IoC容器中实例化Bean引用。 ④ setPropertyValues方法属性依赖注入:遍历PropertyValues属性集合,调用setPropertyValue方法设置属性值。
9. BeanWrapperImpl类之setPropertyValue方法真正注入属性值
// 真正依赖注入属性值
@SuppressWarnings("unchecked")
private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
// 获取属性名称
String propertyName = tokens.canonicalName;
// 获取全名称
String actualName = tokens.actualName;
// keys是用来保存集合类型属性的size
if (tokens.keys != null) {
// Apply indexes and map keys: fetch value for all keys but the last one.
PropertyTokenHolder getterTokens = new PropertyTokenHolder();
getterTokens.canonicalName = tokens.canonicalName;
getterTokens.actualName = tokens.actualName;
getterTokens.keys = new String[tokens.keys.length - 1];
System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
Object propValue;
try {
// 获取属性值,该方法内部使用JDK的内省( Introspector)机制,
// 调用属性的getter(readerMethod)方法,获取属性的值
propValue = getPropertyValue(getterTokens);
}
catch (NotReadablePropertyException ex) {
throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
"Cannot access indexed value in property referenced " +
"in indexed property path '" + propertyName + "'", ex);
}
// 获取集合长度
String key = tokens.keys[tokens.keys.length - 1];
if (propValue == null) {
// null map value case
if (this.autoGrowNestedPaths) {
// TODO: cleanup, this is pretty hacky
int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex);
propValue = setDefaultValue(getterTokens);
}
else {
throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
"Cannot access indexed value in property referenced " +
"in indexed property path '" + propertyName + "': returned null");
}
}
// 属性值类型为数组类型
if (propValue.getClass().isArray()) {
// 获取属性的描述符
PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
// 获取数组类型
Class> requiredType = propValue.getClass().getComponentType();
// 获取数组长度
int arrayIndex = Integer.parseInt(key);
Object oldValue = null;
try {
if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
oldValue = Array.get(propValue, arrayIndex);
}
// 将属性的值赋值给数组中的元素
Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(),
requiredType, TypeDescriptor.nested(property(pd), tokens.keys.length));
Array.set(propValue, arrayIndex, convertedValue);
}
catch (IndexOutOfBoundsException ex) {
throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
"Invalid array index in property path '" + propertyName + "'", ex);
}
}
// 属性值类型为List集合类型
else if (propValue instanceof List) {
PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
// 获取list集合类型
Class> requiredType = GenericCollectionTypeResolver.getCollectionReturnType(
pd.getReadMethod(), tokens.keys.length);
List list = (List) propValue;
// 获取list集合size
int index = Integer.parseInt(key);
Object oldValue = null;
if (isExtractOldValueForEditor() && index < list.size()) {
oldValue = list.get(index);
}
// 获取list解析后的属性值
Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(),
requiredType, TypeDescriptor.nested(property(pd), tokens.keys.length));
int size = list.size();
// 如果list的长度大于属性值的长度,将多余的位置赋值为null
if (index >= size && index < this.autoGrowCollectionLimit) {
for (int i = size; i < index; i++) {
try {
list.add(null);
}
catch (NullPointerException ex) {
throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
"Cannot set element with index " + index + " in List of size " +
size + ", accessed using property path '" + propertyName +
"': List does not support filling up gaps with null elements");
}
}
list.add(convertedValue);
}
else {
try {
// 使用下标设置属性值
list.set(index, convertedValue);
}
catch (IndexOutOfBoundsException ex) {
throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
"Invalid list index in property path '" + propertyName + "'", ex);
}
}
}
// 属性值类型为Map集合类型
else if (propValue instanceof Map) {
PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
// 获取Map集合key类型
Class> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(
pd.getReadMethod(), tokens.keys.length);
// 获取Map集合value类型
Class> mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(
pd.getReadMethod(), tokens.keys.length);
Map map = (Map) propValue;
TypeDescriptor typeDescriptor = (mapKeyType != null ?
TypeDescriptor.valueOf(mapKeyType) : TypeDescriptor.valueOf(Object.class));
// 解析Map类型属性key值
Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor);
Object oldValue = null;
if (isExtractOldValueForEditor()) {
oldValue = map.get(convertedMapKey);
}
// 解析Map类型属性value值
Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(),
mapValueType, TypeDescriptor.nested(property(pd), tokens.keys.length));
// 将解析后的key和value值赋值给Map集合属性
map.put(convertedMapKey, convertedMapValue);
}
else {
throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
"Property referenced in indexed property path '" + propertyName +
"' is neither an array nor a List nor a Map; returned value was [" + pv.getValue() + "]");
}
}
// 属性类型为非集合类型注入
else {
// 获取属性值的描述
PropertyDescriptor pd = pv.resolvedDescriptor;
if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
// 如果属性描述为空或者属性的setter方法也为空
if (pd == null || pd.getWriteMethod() == null) {
//如果属性值是可选的,则返回(忽略该属性值)
if (pv.isOptional()) {
logger.debug("Ignoring optional value for property '" + actualName +
"' - property not found on bean class [" + getRootClass().getName() + "]");
return;
}
else { // 否则抛出不可写属性异常NotWritablePropertyException
PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
throw new NotWritablePropertyException(
getRootClass(), this.nestedPath + propertyName,
matches.buildErrorMessage(), matches.getPossibleMatches());
}
}
// 设置缓存属性解析描述为pd
pv.getOriginalPropertyValue().resolvedDescriptor = pd;
}
Object oldValue = null;
try {
Object originalValue = pv.getValue();
Object valueToApply = originalValue;
if (!Boolean.FALSE.equals(pv.conversionNecessary)) {
if (pv.isConverted()) {
valueToApply = pv.getConvertedValue();
}
else {
if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
// 利用JDK内省机制获取属性的getter方法
final Method readMethod = pd.getReadMethod();
// 如果属性的getter方法不是public访问控制权限的
// 那么使用JDK的反射机制强行访问非public的方法(暴力读取属性值)
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) &&
!readMethod.isAccessible()) {
if (System.getSecurityManager()!= null) {
// 匿名内部类,根据权限修改属性的读取控制限制
AccessController.doPrivileged(new PrivilegedAction() {
@Override
public Object run() {
readMethod.setAccessible(true);
return null;
}
});
}
else {
readMethod.setAccessible(true);
}
}
try {
// 属性没有提供getter方法时,调用潜在的读取属性值的方法,获取属性值
if (System.getSecurityManager() != null) {
oldValue = AccessController.doPrivileged(new PrivilegedExceptionAction() {
@Override
public Object run() throws Exception {
return readMethod.invoke(object);
}
}, acc);
}
else {
oldValue = readMethod.invoke(object);
}
}
catch (Exception ex) {
if (ex instanceof PrivilegedActionException) {
ex = ((PrivilegedActionException) ex).getException();
}
if (logger.isDebugEnabled()) {
logger.debug("Could not read previous value of property '" +
this.nestedPath + propertyName + "'", ex);
}
}
}
// 解析属性值
valueToApply = convertForProperty(propertyName, oldValue, originalValue, pd, new TypeDescriptor(property(pd)));
}
// 设置属性的注入值
pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue);
}
// 根据JDK的内省机制,获取属性的setter(写方法)方法
final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor ?
((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess() :
pd.getWriteMethod());
// 如果属性的setter方法是非public,即访问控制权限比较严格,则使用JDK的反射机制,
// 强行设置setter方法可访问(暴力为属性赋值)
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers()) && !writeMethod.isAccessible()) {
if (System.getSecurityManager()!= null) {
AccessController.doPrivileged(new PrivilegedAction() {
@Override
public Object run() {
writeMethod.setAccessible(true);
return null;
}
});
}
else {
writeMethod.setAccessible(true);
}
}
final Object value = valueToApply;
if (System.getSecurityManager() != null) {
try {
// 将属性值设置到属性字段上
AccessController.doPrivileged(new PrivilegedExceptionAction() {
@Override
public Object run() throws Exception {
writeMethod.invoke(object, value);
return null;
}
}, acc);
}
catch (PrivilegedActionException ex) {
throw ex.getException();
}
}
else {
writeMethod.invoke(this.object, value);
}
}
catch (TypeMismatchException ex) {
throw ex;
}
catch (InvocationTargetException ex) {
PropertyChangeEvent propertyChangeEvent =
new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue());
if (ex.getTargetException() instanceof ClassCastException) {
throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException());
}
else {
throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
}
}
catch (Exception ex) {
PropertyChangeEvent pce =
new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue());
throw new MethodInvocationException(pce, ex);
}
}
}
说明: ① 对于集合类型的属性注入,直接将解析的属性值添加给集合中的元素。 ② 对于非集合类型的属性注入,使用jdk的反射和内省机制设置权限,通过getter方法获取属性以前的值,通过setter方法为属性设置注入后的值。如果权限不够,那么就使用setAccessible(true)暴力反射。
spring IOC的抽象容器,BeanFactory是定义的一个抽象工厂类,用于管理Bean,如维护bean,bean的配置,bean之间的关系等,该接口只是抽象规范了所有的行为,至于具体的实现由各自的需求而定,比如DefaultListableBeanFactory、XmlBeanFactory、ClasspathXmlApplicationContext等(不同管理bean的工厂)。
package spark.examples.scala.grammars.caseclasses
object CaseClass_Test00 {
def simpleMatch(arg: Any) = arg match {
case v: Int => "This is an Int"
case v: (Int, String)