源码分析基于spring 4.3.x
前面已经描述了spring加载配置文件的过程,现在来分析一下spring构建bean的过程。
接口结构
beanFactory.png
(图中以BeanFactory结尾的接口都继承了BeanFactory接口)
BeanFactory是访问Spring bean容器的根接口,提供getBean方法, spring按不同的功能给他添加了很多子接口, 如HierarchicalBeanFactory(有层级的),AutowireCapableBeanFactory(自动装配)等。
ListableBeanFactory是列表相关的(Listable), 该BeanFactory提供了列举所有bean实例的方法,如获取所以的bean name
ConfigurableBeanFactory是配置相关的,它提供了配置BeanFactory的相关方法,如setCacheBeanMetadata,setCurrentlyInCreation等。
BeanDefinitionRegistry提供bean注册到spring上下文的接口,前面讲解spring加载配置时说过注册方法DefaultListableBeanFactory.registerBeanDefinition就是该接口的实现。
栗子
Blog bean = (Blog)xmlBeanFactory.getBean("blog");
XmlBeanFactory继承了AbstractBeanFactory,getBean
将调用AbstractBeanFactory.doGetBean方法。该方法是构建bean的具体实现。
AbstractBeanFactory.doGetBean:
protected <T> T doGetBean(final String name, final Class<T> requiredType,
final Object[] args, boolean typeCheckOnly) {
final String beanName = transformedBeanName(name); // 处理别名
Object sharedInstance = getSingleton(beanName); // 代码1 从单例缓存中获取
if (sharedInstance != null && args == null) {
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
} else {
// 如果已经在创建这个bean,则直接失败,这时很可能陷入循环引用了
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// 父Factory
BeanFactory parentBeanFactory = getParentBeanFactory();
// Check if bean definition exists in this factory.
// 如果在所有已经加载的类中没有beanName则会尝试从parentBeanFactory中检测
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
// 将存储XML配置文件的GernericBeanDefinition转换成RootBeanDefinition,如果BeanName是子Bean的话会合并父类的相关属性
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// 处理依赖
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
getBean(dep);
}
}
// bean范围为Singleton
if (mbd.isSingleton()) {
// 代码2
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args); // 代码3 创建bean
} catch (BeansException ex) {
...
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
} else if(mbd.isPrototype()) { // 其他处理
...
}
}
// 类型检查
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
try {
// 类型转化
return getTypeConverter().convertIfNecessary(bean, requiredType);
}
catch (TypeMismatchException ex) {
...
}
}
return (T) bean;
}
spring bean有singleton/prototype等范围,这里只关注singleton对象的创建
getObjectForBeanInstance
方法会根据参数beanInstance进行处理,如果beanInstance是FactoryBean,会调用其getObject()
方法创建bean,如果不是,返回直接返回该beanInstance参数。
FactoryBean是spring提供的一个扩展接口,用户实现该接口自定义bean的创建。
需要注意,上面代码调用了重载方法 getSingleton(String beanName)
和getSingleton(String beanName, ObjectFactory<?> singletonFactory)
重载方法一getSingleton(beanName)
从容器中获取已缓存的单例bean(代码1处)。
DefaultSingletonBeanRegistry.getSingleton:
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 != NULL_OBJECT ? singletonObject : null);
}
singletonObject,earlySingletonObjects,singletonFactories都是简单的map,缓存了单例的bean,
正在创建的bean和ObjectFactory对象。
重载方法二getSingleton(String beanName, ObjectFactory<?> singletonFactory)
会通过ObjectFactory创建一个单例bean。
上面代码2处会调用DefaultSingletonBeanRegistry.getSingleton(String beanName, ObjectFactory<?> singletonFactory)
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
// 仅做错误检查,子类可扩展
beforeSingletonCreation(beanName);
boolean newSingleton = false;
try {
// 创建bean
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
...
finally {
afterSingletonCreation(beanName);
}
if (newSingleton) {
// 将bean加入到singletonObject等缓存中
addSingleton(beanName, singletonObject);
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
}
代码3处,singletonFactory.getObject()
才是真正创建bean的关键,上面代码中singletonFactory是一个匿名类, 真正的bean创建过程在return createBean(beanName, mbd, args);
代码中,
createBean
方法由AbstractAutowireCapableBeanFactory实现:
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
RootBeanDefinition mbdToUse = mbd;
// 解析bean的Class
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd); // 复制BeanDefinition
mbdToUse.setBeanClass(resolvedClass);
}
// 预处理 method overrides.
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
...
}
// 注意,如果resolveBeforeInstantiation返回非null对象,这里将直接返回
try {
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
} catch (Throwable ex) {
...
}
// 创建bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
return beanInstance;
}
resolveBeforeInstantiation调用BeanPostProcessors处理。
BeanPostProcessor接口也是spring提供的扩展接口,该接口有两个方法postProcessBeforeInitialization和postProcessAfterInitialization,用户可以实现该接口,就可以在spring完成Bean的创建工作前后分别添加自己的逻辑处理。
注意:如果BeanPostProcessor.postProcessBeforeInitialization返回非null对象,spring将不再创建对象,而使用该返回对象作为目标bean。
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
// // 查找目标class
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
// 应用BeanPostProcessors
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
// 查找spring上下文中所以的BeanPostProcessors
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// BeanPostProcessors处理
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
BeanPostProcessors返回结果为null,就通过AbstractAutowireCapableBeanFactory.doCreateBean创建bean:
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
BeanWrapper instanceWrapper = null;
// 创建属性为空的bean
instanceWrapper = createBeanInstance(beanName, mbd, args);
// MergedBeanProcessor处理
if (!mbd.postProcessed) {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
mbd.postProcessed = true;
}
Object exposedObject = bean;
// 注入属性
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
// 处理扩展接口
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
registerDisposableBeanIfNecessary(beanName, bean, mbd);
return exposedObject;
}
这里涉及到循环引用的处理,比较繁琐,所以省略了很多代码,只保留bean创建相关的代码。
MergedBeanDefinitionPostProcessor也是spring提供的扩展接口。主要框架内部使用。
构造bean
createBeanInstance
通过反射生成一个bean(属性还没有注入)
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
// Make sure bean class is actually resolved at this point.
Class<?> beanClass = resolveBeanClass(mbd, beanName);
//
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
return instantiateBean(beanName, mbd);
}
}
// Need to determine the constructor...
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
// No special handling: simply use no-arg constructor.
return instantiateBean(beanName, mbd);
}
如果是重新创建同一个bean,spring会利用已选择的构造方法。否则,spring要执行选择构造方法
autowireConstructor(beanName, mbd, ctors, args)
会根据参数选择合适的构造方法,方法逻辑非常复杂,这里不展开。
instantiateBean引用无参构造方法
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
Object beanInstance;
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent); // 创建bena
BeanWrapper bw = new BeanWrapperImpl(beanInstance); // 创建beanWrapper
initBeanWrapper(bw); // 注册用户自定义的处理器
return bw;
} cache(Throwable ex) {
...
}
}
getInstantiationStrategy()
获取到CglibSubclassingInstantiationStrategy,CglibSubclassingInstantiationStrategy继承了 SimpleInstantiationStrategy,getInstantiationStrategy().instantiate
调用到
SimpleInstantiationStrategy.instantiate:
public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
// Don't override the class with CGLIB if no overrides.
if (bd.getMethodOverrides().isEmpty()) {
Constructor<?> constructorToUse;
synchronized (bd.constructorArgumentLock) {
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
if (constructorToUse == null) {
// 获取class
final Class<?> clazz = bd.getBeanClass();
try {
// 获取构造方法
constructorToUse = clazz.getDeclaredConstructor((Class[]) null);
}
catch (Throwable ex) {
...
}
}
}
// 返回实例
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// Must generate CGLIB subclass.
return instantiateWithMethodInjection(bd, beanName, owner);
}
}
BeanUtils.instantiateClass就非常简单了
public static <T> T instantiateClass(Constructor<T> ctor, Object... args)... {
ReflectionUtils.makeAccessible(ctor);
return ctor.newInstance(args); // 返回实例
}
注入属性
在读取配置时,已经将属性的propername,type等基本消息读取存放到PropertyValues中,
而populateBean
方法则解析属性的值,并注入到bean中。
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
PropertyValues pvs = mbd.getPropertyValues(); // 已从配置中读取的属性信息
boolean continueWithPropertyPopulation = true;
// InstantiationAwareBeanPostProcessor处理
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
if (!continueWithPropertyPopulation) {
return;
}
// 解析自动注入的属性
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// 通过bean name自动注入
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// 通过bean type自动注入
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
// 根据需要进行postProcesst处理
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
// 将值注到bean中
applyPropertyValues(beanName, mbd, bw, pvs);
}
InstantiationAwareBeanPostProcessor也是spring提供的扩展接口,它继承自BeanPostProcessor,并添加了postProcessBeforeInstantiation,postProcessAfterInstantiation,postProcessPropertyValues这三个方法。
先看一下通过bean name自动注入
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
for (String propertyName : propertyNames) {
Object bean = getBean(propertyName); // 获取bean
pvs.add(propertyName, bean); // 将bean添加到属性中
registerDependentBean(propertyName, beanName); // 声明依赖
}
}
就是根据propertyName获取对应的bean,并注入到PropertyValues中。
autowireByType
这里就不复述了。
属性处理分为两个步骤
- 解析
- 转换
接口结构
propertyValues.png比较简单,就不多说了。
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
MutablePropertyValues mpvs = null;
List<PropertyValue> original;
if (pvs instanceof MutablePropertyValues) {
mpvs = (MutablePropertyValues) pvs;
if (mpvs.isConverted()) { // 如果已经转换了,不再处理
bw.setPropertyValues(mpvs); // 赋值
return;
}
original = mpvs.getPropertyValueList(); // 获取最初的配置值
}
else {
original = Arrays.asList(pvs.getPropertyValues());
}
// 使用用户定义的TypeConverter
TypeConverter converter = getCustomTypeConverter();
// 使用默认的TypeConverter
if (converter == null) {
converter = bw;
}
// Value解析器
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
// 存储结果
List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size());
boolean resolveNecessary = false;
for (PropertyValue pv : original) {
if (pv.isConverted()) { // 已转换,不用再处理
deepCopy.add(pv);
}
else {
String propertyName = pv.getName();
Object originalValue = pv.getValue();
// 解析
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
Object convertedValue = resolvedValue;
// 转化
boolean convertible = bw.isWritableProperty(propertyName) &&
!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
if (convertible) {
convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
}
// 复制结果
if (resolvedValue == originalValue) {
if (convertible) {
pv.setConvertedValue(convertedValue);
}
deepCopy.add(pv);
}
else if (convertible && originalValue instanceof TypedStringValue &&
!((TypedStringValue) originalValue).isDynamic() &&
!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
pv.setConvertedValue(convertedValue);
deepCopy.add(pv);
}
else {
resolveNecessary = true;
deepCopy.add(new PropertyValue(pv, convertedValue));
}
}
}
if (mpvs != null && !resolveNecessary) {
mpvs.setConverted();
}
// 赋值
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
}
解析
BeanDefinitionValueResolver.resolveValueIfNecessary负责解析,如ref会解析为对应的bean,list标签会解析为ArrayList等
public Object resolveValueIfNecessary(Object argName, Object value) {
if (value instanceof RuntimeBeanReference) {
// 解析ref标签
RuntimeBeanReference ref = (RuntimeBeanReference) value;
return resolveReference(argName, ref);
}
else if (value instanceof RuntimeBeanNameReference) {
// 解析RuntimeBeanNameReference
}
else if (value instanceof BeanDefinitionHolder) {
// 解析BeanDefinitionHolder
}
else if (value instanceof BeanDefinition) {
// 解析BeanDefinition
}
else if (value instanceof ManagedArray) {
// 解析数组
}
else if (value instanceof ManagedList) {
// 解析List
}
...
}
可以看到,这里对各种类型的属性做了解析。
注意,这里只是解析,没有做类型转化,如bean实际属性是int[],但这里的解析结果是ArrayList<String>
转化
下面看看转化过程
private Object convertForProperty(Object value, String propertyName, BeanWrapper bw, TypeConverter converter) {
if (converter instanceof BeanWrapperImpl) {
// 使用默认的TypeConverter
return ((BeanWrapperImpl) converter).convertForProperty(value, propertyName);
}
else {
// 使用用户定义的TypeConverter
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
return converter.convertIfNecessary(value, pd.getPropertyType(), methodParam);
}
}
看看默认的转化BeanWrapperImpl.convertForProperty
public Object convertForProperty(Object value, String propertyName) throws TypeMismatchException {
CachedIntrospectionResults cachedIntrospectionResults = getCachedIntrospectionResults();
PropertyDescriptor pd = cachedIntrospectionResults.getPropertyDescriptor(propertyName);
TypeDescriptor td = cachedIntrospectionResults.getTypeDescriptor(pd);
return convertForProperty(propertyName, null, value, td);
}
protected Object convertForProperty(String propertyName, Object oldValue, Object newValue, TypeDescriptor td)
throws TypeMismatchException {
return convertIfNecessary(propertyName, oldValue, newValue, td.getType(), td);
}
private Object convertIfNecessary(String propertyName, Object oldValue, Object newValue, Class<?> requiredType,
TypeDescriptor td) throws TypeMismatchException {
return this.typeConverterDelegate.convertIfNecessary(propertyName, oldValue, newValue, requiredType, td);
}
CachedIntrospectionResults是对bean的class元信息的解析结果缓存,getCachedIntrospectionResults会查询缓存,如果缓存没有,就创建一个CachedIntrospectionResults。
PropertyDescriptor是对bean的class中属性的描述,有getter/setter方法名,方法引用,属性类型等信息。
convertIfNecessary最终调用到TypeConverterDelegate.convertIfNecessary
public <T> T convertIfNecessary(String propertyName, Object oldValue, Object newValue,
Class<T> requiredType, TypeDescriptor typeDescriptor) throws IllegalArgumentException {
// 用户是否对该requiredType自定义了PropertyEditor
PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName);
ConversionFailedException conversionAttemptEx = null;
// 用户是否自定义了ConversionService
ConversionService conversionService = this.propertyEditorRegistry.getConversionService();
if (editor == null && conversionService != null && newValue != null && typeDescriptor != null) {
TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) {
// ConversionService可以自定义转换,则使用ConversionService
return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor);
}
}
Object convertedValue = newValue;
// 存在用户自定义的editor或不支持直接转换
if (editor != null || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) {
if (editor == null) {
// 获取默认的editor
editor = findDefaultEditor(requiredType);
}
// 使用editor转化
convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor);
}
boolean standardConversion = false;
// PropertyEditor转化后,继续处理
if (requiredType != null) {
// Try to apply some standard type conversion rules if appropriate.
if (convertedValue != null) {
if (Object.class == requiredType) {
return (T) convertedValue;
}
else if (requiredType.isArray()) {
// 转换数组
...
return (T) convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType());
}
else if (convertedValue instanceof Collection) {
// 转换Collection
convertedValue = convertToTypedCollection(
(Collection<?>) convertedValue, propertyName, requiredType, typeDescriptor);
standardConversion = true;
}
else if (convertedValue instanceof Map) {
// 转换map
convertedValue = convertToTypedMap(
(Map<?, ?>) convertedValue, propertyName, requiredType, typeDescriptor);
standardConversion = true;
}
if (String.class == requiredType && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) {
// 转换String
return (T) convertedValue.toString();
}
else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) {
if (conversionAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) {
// 使用参数为string的构建方法构建对象
Constructor<T> strCtor = requiredType.getConstructor(String.class);
return BeanUtils.instantiateClass(strCtor, convertedValue);
}
}
else if (convertedValue instanceof Number && Number.class.isAssignableFrom(requiredType)) {
// 转换为number
convertedValue = NumberUtils.convertNumberToTargetClass(
(Number) convertedValue, (Class<Number>) requiredType);
standardConversion = true;
}
}
else {
// convertedValue == null
if (javaUtilOptionalEmpty != null && requiredType == javaUtilOptionalEmpty.getClass()) {
convertedValue = javaUtilOptionalEmpty;
}
}
}
return (T) convertedValue;
}
这里可以看到, 即使使用了PropertyEditor转化了,spring还会根据requiredType进行了各种处理。
这里spring提供了多个扩展接口, TypeConverter,ConversionService和PropertyEditor。
用户可以实现这些接口, 对属性转化过程处理。
线程安全值得注意: 使用线程安全的spring类型转换器ConversionService VS TypeConverter
扩展处理
回顾AbstractAutowireCapableBeanFactory.doCreateBean方法,下一步就是initializeBean了
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
// 调用BeanNameAware,BeanClassLoaderAware,BeanFactoryAware的set方法
invokeAwareMethods(beanName, bean);
// ProcessorsBeforeInitialization方法
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
// 调用init-method方法
invokeInitMethods()
// 调用后处理器BeanPostProcessorsAfterInitialization.postProcessAfterInitialization
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
这个方法主要是处理各种各样的扩展接口。
invokeAwareMethods是对各种Aware扩展接口处理。
applyBeanPostProcessorsBeforeInitialization/applyBeanPostProcessorsAfterInitialization是对BeanPostProcessor扩展接口处理。
invokeInitMethods是对InitializingBean扩展接口处理。
registerDisposableBeanIfNecessary
方法主要是注册其DisposableBean接口或bean销毁回调方法,这里不再深入。
到这里, spring构建bean的简单流程就讲完了。可以看到, spring准备了很多扩展接口,提供给用户去自定义bean的构建。
错误之处,还忘指出。
网友评论