概述
1:写在前面
本文在spring通过不同的方式创建bean的基础上进行分析,作为补充,详细分析spring是如何填充属性到bean中的。
2:populateBean
方法位置org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean
,源码如下:
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean
...snip...
try {
// <2021-03-27 09:19>
// 填充属性信息
populateBean(beanName, mbd, instanceWrapper);
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
...snip...
}
<2021-03-27 09:19>
处就是我们本文要分析的,填充属性值,源码如下:
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
// 异常情况,这里可以认为bw不会为null
if (bw == null) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
return;
}
}
// 满足以下条件才进入
// 1:不是应用程序本身的bean,即!mbd.isSynthetic()
// 2:存在InstantiationAwareBeanPostProcessor,即hasInstantiationAwareBeanPostProcessors()
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
// 获取所有的BeanPPostProcessor,不止InstantiationAwareBeanPostProcessor,循环
for (BeanPostProcessor bp : getBeanPostProcessors()) {
// InstantiationAwareBeanPostProcessor类型才处理
// 因为获取的所有的BeanPPostProcessor,不止InstantiationAwareBeanPostProcessor,所以需要进行类型的判断
if (bp instanceof InstantiationAwareBeanPostProcessor) {
// 确定是,强转
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// postProcessAfterInstantiation方法控制
// 是否还需要执行后续的填充属性的工作,如果是false
// 即不需要,则直接return
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
}
// 获取封装对象属性信息的对象,即<bean>标签的<property>子标签
// 定义的信息
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
// 获取解析模式,BY_TYPE,BY_NAME
// 处理的是其他bean的引用的情况,基础数据类型,这里为false
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
// <2021-03-28 07:25>
// 目前的自动注入方式有以下的四种
// 1:no 2:byType 3:byName 4:constructor
// 这里处理的情况为,byName,byType两种
// 此时需要找到目标bean来注入到属性中
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
// 封装为MutablePropertyValues,支持对属性的简单操作
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// <2021-03-28 07:28>
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// <2021-03-28 07:29>
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
// 赋值新的pvs
pvs = newPvs;
}
// 是否有InstantiationAwareBeanPostProcessor
// 有则调用其postProcessProperties,在设置属性前,修改
// 要设置的值
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
// 有InstantiationAwareBeanPostProcessor
if (hasInstAwareBpps) {
// 无pvs,则创建,防止bp发生NPE
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (BeanPostProcessor bp : getBeanPostProcessors()) {
// InstantiationAwareBeanPostProcessor类型才处理
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 获取修改后的pvs
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
// 为空
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
// 再尝试通过postProcessPropertyValues方法获取pvs,因为用户也有可能通过该老版本方法获取对象
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
// 还为空,则return,没有必要再走下去了,因为没有任何参数
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
}
// 是否需要依赖检查
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
checkDependencies(beanName, mbd, filteredPds, pvs);
}
// <2021-03-28 16:08>
if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
<2021-07-27 13:05>
处是在实例化后设置属性前,执行操作,关于InstantiationAwareBeanPostProcessor可以参考这里。<2021-03-28 07:25>
处是处理byType,byName的自动注入方式,关于自动注入的方式可以参考这里。<2021-03-28 07:28>
处是通过name方式自动注入,具体参考2.1:byName方式自动注入
。<2021-03-28 07:29>
处是通过类型方式自动注入,具体参考2.2:byType方式自动注入
。<2021-03-28 16:08>
处是将pvs应用到bw中,具体参考2.3:应用pvs到bw中
。
2.1:byName方式自动注入
当配置文件为如下如下可能配置时,就会按照byName
的方式来给属性自动注入值:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="state" class="yudaosourcecode.autowiretest.State"/>
<bean id="state1" class="yudaosourcecode.autowiretest.State"/>
<bean id="country"
class="yudaosourcecode.autowiretest.Country"
autowire="byName"/>
</beans>
看下源码:
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#autowireByName
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
// <2021-03-28 08:19>
// 获取需要注入的对象类型属性
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
// 遍历需要注入的属性名称数组
for (String propertyName : propertyNames) {
// <2021-03-28 08:57>
// 容器中是否包含propertyName,即需要注入的bean名称
if (containsBean(propertyName)) {
// 递归获取bean
Object bean = getBean(propertyName);
// 存储值到pvs中
pvs.add(propertyName, bean);
// <2021-03-28 08:55>
// 存储名称的依赖和被依赖的关系
registerDependentBean(propertyName, beanName);
if (logger.isTraceEnabled()) {
logger.trace("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");
}
}
}
}
<2021-03-28 08:19>
处是获取需要注入的属性,源码如下:
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#unsatisfiedNonSimpleProperties
protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) {
// 结果集合
Set<String> result = new TreeSet<>();
// 属性值
PropertyValues pvs = mbd.getPropertyValues();
// 获取属性对应的属性描述器数组
PropertyDescriptor[] pds = bw.getPropertyDescriptors();
// 遍历
for (PropertyDescriptor pd : pds) {
// 满足以下条件则是需要注入的属性
// 1:pd.getWriteMethod() != null有写方法,即setter
// 2:!isExcludedFromDependencyCheck(pd),依赖检查中没有被忽略
// 3:pvs不包含该属性名称,即没有通过<property>标签定义
// 4:不是基础数据类型,Date,URL,NUMBER等类型
if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) &&
!BeanUtils.isSimpleProperty(pd.getPropertyType())) {
// 添加
result.add(pd.getName());
}
}
// 转数组
return StringUtils.toStringArray(result);
}
<2021-03-28 08:57>
处是判断容器中是否包含待注入的bean,源码如下:
org.springframework.beans.factory.support.AbstractBeanFactory#containsBean
public boolean containsBean(String name) {
// 处理别名,转换为标准bean名称
String beanName = transformedBeanName(name);
// 如果是在单例一级缓存中存在 或者是
// 在bean定义的map中存在
if (containsSingleton(beanName) || containsBeanDefinition(beanName)) {
// 名称是不是以&开头,即获取工厂bean的名称
// 或者是
// 是工厂bean
return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(name));
}
// 没有找到的话,则尝试从父容器中查找
BeanFactory parentBeanFactory = getParentBeanFactory();
return (parentBeanFactory != null && parentBeanFactory.containsBean(originalBeanName(name)));
}
<2021-03-28 08:55>
处是存储依赖和被依赖的关系,主要用于bean销毁时,同时销毁依赖的不再需要的bean,源码如下:
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#registerDependentBean
public void registerDependentBean(String beanName, String dependentBeanName) {
// 获取bean的标准bean名称
String canonicalName = canonicalName(beanName);
// 存储依赖自己的bean的map
synchronized (this.dependentBeanMap) {
Set<String> dependentBeans =
this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>(8));
if (!dependentBeans.add(dependentBeanName)) {
return;
}
}
// 存储自己依赖的bean的map
synchronized (this.dependenciesForBeanMap) {
Set<String> dependenciesForBean =
this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet<>(8));
dependenciesForBean.add(canonicalName);
}
}
2.2:byType方式自动注入
当配置文件为如下如下可能配置时,就会按照byType
的方式来给属性自动注入值:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="state" class="yudaosourcecode.autowiretest.State"/>
<bean id="state1" class="yudaosourcecode.autowiretest.State" autowire-candidate="false"/>
<bean id="country"
class="yudaosourcecode.autowiretest.Country"
autowire="byType"/>
</beans>
源码如下:
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#autowireByType
protected void autowireByType(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
// 获取类型转换器,用于取代PropertyEditor机制
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
// 自动注入的bean名称集合
Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
// 获取需要自动注入的属性名称
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
// 遍历需要注入的属性名称数组
for (String propertyName : propertyNames) {
try {
// 获取属性对应的属性描述器
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
// 如果是Object类型则不处理,因为给Object类型引用赋值没有任何意义
// 这里有可能是个坑,使用byType方式时要注意
if (Object.class != pd.getPropertyType()) {
// 获取写方法,即setter的参数
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
// 暂时不知道什么意思,可以认为结果为true
boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered);
// 获取依赖描述器
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
// <2021-03-28 09:43>
// 根据类型解析需要注入的bean
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
// 添加到pvs中
if (autowiredArgument != null) {
pvs.add(propertyName, autowiredArgument);
}
// 注册依赖和被依赖的关系,便于在bean销毁时也可以销毁
// 依赖的bean,理论上满足注入要求的bean只可能有一个,
// 不是很清楚为什么这里会考虑存在多个的情况
for (String autowiredBeanName : autowiredBeanNames) {
// 注册bean名称和依赖bean名称之间的依赖关系
registerDependentBean(autowiredBeanName, beanName);
if (logger.isTraceEnabled()) {
logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
propertyName + "' to bean named '" + autowiredBeanName + "'");
}
}
// 清空当前bean依赖的bean集合
autowiredBeanNames.clear();
}
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
}
}
}
<2021-03-28 09:43>
处是根据类型解析出需要注入的bean名称,具体参考2.2.1:根据类型获取满足要求的bean名称
。
2.2.1:根据类型获取满足要求的bean名称
源码如下:
org.springframework.beans.factory.support.DefaultListableBeanFactory#resolveDependency
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
// 注册参数名称探测者
descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
// 处理依赖类型为Option类型
if (Optional.class == descriptor.getDependencyType()) {
return createOptionalDependency(descriptor, requestingBeanName);
}
// 如果是ObjectFactory或者是ObjectProvider,间接获取
// 获取对象,但是可以对原生对象做一些操作,例如进行代理,等
else if (ObjectFactory.class == descriptor.getDependencyType() ||
ObjectProvider.class == descriptor.getDependencyType()) {
return new DependencyObjectProvider(descriptor, requestingBeanName);
}
// 类似于ObjecFactory,ObjectProvider,提供了不同的
// 用于获取对象的API
else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
}
else {
// 不清楚具体作用,但是看实现都是返回null,这里按照肯定为null看待
Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
descriptor, requestingBeanName);
if (result == null) {
// <2021-03-28 14:50>
result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
}
return result;
}
}
<2021-03-28 14:50>
处是真正完成按照类型解析bean的位置,是核心代码,源码如下:
org.springframework.beans.factory.support.DefaultListableBeanFactory#doResolveDependency
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
// 注入点,可以认为为null
InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
try {
// 快捷方式,可以认为为null
Object shortcut = descriptor.resolveShortcut(this);
if (shortcut != null) {
return shortcut;
}
// 依赖的bean的类型
Class<?> type = descriptor.getDependencyType();
// 为null,忽略
Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
// 为null,忽略
if (value != null) {
if (value instanceof String) {
String strVal = resolveEmbeddedValue((String) value);
BeanDefinition bd = (beanName != null && containsBean(beanName) ?
getMergedBeanDefinition(beanName) : null);
value = evaluateBeanDefinitionString(strVal, bd);
}
TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
try {
return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
}
catch (UnsupportedOperationException ex) {
// A custom TypeConverter which does not support TypeDescriptor resolution...
return (descriptor.getField() != null ?
converter.convertIfNecessary(value, type, descriptor.getField()) :
converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
}
}
// 处理Array,Map等类型的bean
Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
// 存在则直接返回
if (multipleBeans != null) {
return multipleBeans;
}
// 查找和类型相匹配的bean,key:beanName value:bean实例
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
// 没有找到则检测是否必须,若必须,则抛出异常
if (matchingBeans.isEmpty()) {
if (isRequired(descriptor)) {
raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
}
return null;
}
String autowiredBeanName;
Object instanceCandidate;
// 如果有多个
if (matchingBeans.size() > 1) {
// 按照优先级,获取一个优先级最高的
autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
if (autowiredBeanName == null) {
if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
}
else {
// In case of an optional Collection/Map, silently ignore a non-unique case:
// possibly it was meant to be an empty collection of multiple regular beans
// (before 4.3 in particular when we didn't even look for collection beans).
return null;
}
}
instanceCandidate = matchingBeans.get(autowiredBeanName);
}
else {
// We have exactly one match.
Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
autowiredBeanName = entry.getKey();
instanceCandidate = entry.getValue();
}
if (autowiredBeanNames != null) {
autowiredBeanNames.add(autowiredBeanName);
}
if (instanceCandidate instanceof Class) {
instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
}
Object result = instanceCandidate;
if (result instanceof NullBean) {
if (isRequired(descriptor)) {
raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
}
result = null;
}
if (!ClassUtils.isAssignableValue(type, result)) {
throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());
}
return result;
}
finally {
ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
}
}
2.3:应用pvs到bw中
源码:
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
// 无信息,则return
if (pvs.isEmpty()) {
return;
}
// 安全机制相关
if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
}
MutablePropertyValues mpvs = null;
// 原始的pvs,其中一个属性对应一个PropertyValue,主要的信息有
// 1:属性的名称org.springframework.beans.PropertyValue#name
// 2:属性原始的值org.springframework.beans.PropertyValue#value
// 3:属性转换后的值org.springframework.beans.PropertyValue#convertedValue
// 4:是否已经完成了转换org.springframework.beans.PropertyValue#converted
// 5:属性是否是可选的org.springframework.beans.PropertyValue#optional
List<PropertyValue> original;
if (pvs instanceof MutablePropertyValues) {
mpvs = (MutablePropertyValues) pvs;
// 如果是已经完成了类型转换
if (mpvs.isConverted()) {
// Shortcut: use the pre-converted values as-is.
try {
// 设置pvs到pws中,然后return结束
bw.setPropertyValues(mpvs);
return;
}
catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
// 赋值原始的pvs
original = mpvs.getPropertyValueList();
}
else {
// 非MutablePropertyValues直接赋值原始pvs
original = Arrays.asList(pvs.getPropertyValues());
}
// 获取用户类型转换器,优先使用
TypeConverter converter = getCustomTypeConverter();
// 如果是用户定义类型转换器为空,则使用bw作为类型转换器
if (converter == null) {
converter = bw;
}
// 获取bean定义的值解析器
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
// pv的深拷贝集合
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();
// 原始值,一般分为以下两种情况
// 1:如果是ref的,这里是封装有对应bean名称的BeanReference对象
// 2:如果是自动注入的,这里就是最终需要的bean对象的引用
Object originalValue = pv.getValue();
// 解析真正的bean对象的引用
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);
}
// 当是自动注入时,这里会为true,设置转换后的值,下次
// 自动注入时就不需要重复转换了
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();
}
// 设置转换后的pvs到bw中,其实这里就是完成注入的地方了
try {
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
}
catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
最后
以上就是热情老虎为你收集整理的处理BeanWrapper填充bean属性的全部内容,希望文章能够帮你解决处理BeanWrapper填充bean属性所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复