- 上面我们讲到了beanDefinition(零件)注册到容器beanDefinitionMap(仓库)的流程。接下来我们会讲解下如何把这些零件组装成产品也就是创建bean。
- 创建bean过程就像组装零件过程一样同样是工厂流程的一部分。针对创建bean我们应该会想到俩个问题:第一它是哪里创建的,第二它又是如何创建的呢。
①、对于第一个问题我们要想获得产品肯定离不开工厂提供的零件、员工及机器等流程,所以创建bean也离不开bean工厂,那么bean工厂必定也会为我们提供创建bean的入口
该入口也就是BeanFactory的getBean方法。
②、现在我们知道bean的创建位置了,接下来我们讨论下如何创建bean,看过源码的小伙伴都知道这是个复杂的过程,讲下创建bean的大概流程:
1️⃣:转换beanName
为什么要转换beanName呢,因为获取bean时的参数可能是别名,也可能是FactoryBean,如果获取FactoryBean则需要在beanName前加上&// FactoryBean->AbstractFactoryBean->getBean->doGetBean Object 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); }
2️⃣:尝试从缓存中加载单例
我们配置bean信息的时候<bean scope='singleton'>
是每个bean的默认属性,表示bean的作用域,默认单例。在单例情况下存在依赖循环的问题,所谓的依赖循环就是A类中有B类属性,B类有A类属性,在初始化A类时会先填充属性B类,那么在初始化B类时就会填充A类,这时A类还没有初始化完成,就会造成依赖循环形成闭环,如下图:
接下来我们会想它是如何解决的并且在哪解决的。首先分析一下它是在哪解决的:
// SingletonBeanRegistry -> DefaultSingletonBeanRegistry(单例缓存容器)
// 单例的缓存(一级缓存) (成品对象缓存)
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
// 单例工厂的缓存(三级缓存) (半成品对象缓存:解决依赖循环)
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
// 提前暴露的单例(二级缓存) (解决AOP依赖循环)
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
这个方法里面的逻辑判断可以体现出解决循环依赖的流程
// SingletonBeanRegistry -> DefaultSingletonBeanRegistry(获取单例)
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
// 此缓存单例是否为空且此bean是否正在创建
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
// allowEarlyReference允许循环依赖的开关
if (singletonObject == null && allowEarlyReference) {
// 这个是为终止属性A的循环依赖而提供的ObjectFactory(模拟A->B->A的依赖过程)
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
// 缓存提前的单例
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
在上面方法的if (singletonObject == null && isSingletonCurrentlyInCreation(beanName))
这个判断为空的时候会走下面的这段代码
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
// 创建bean的核心方法
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// 清除缓存
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
这个方法是获取单例的核心方法
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!)");
}
}
// 当前bean加入到singletonsCurrentlyInCreation(满足终止循环依赖的条件之一)
beforeSingletonCreation(beanName);
boolean newSingleton = false;
try {
// 创建bean操作(createBean):
// 1.此操作包含提前暴露原始bean(已经实例化但还没有填充属性)的引用到singletonFactories(终止循环依赖)
// 2.填充属性(依赖属性的递归调用)
// 3.获取单例的引用earlySingletonReference
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
}
finally {
// 完成bean的加载移除singletonsCurrentlyInCreation的beanName
afterSingletonCreation(beanName);
}
if (newSingleton) {
// 添加缓存到singletonObjects并且从singletonFactories、earlySingletonObjects移除(只保留一级缓存)
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 实例化bean(构造函数)
// 如果配置工厂方法factory-method属性,则使用工厂方法初始化策略
// 带有@Autowired注解的需要调用autowireConstructor方法解析
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
// 解决循环依赖的关键
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");
}
// 暴露原始bean(已经实例化但还没有填充属性)的引用到singletonFactories
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
}
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
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.");
}
}
}
}
// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
上图展示了解决循环依赖的流程
3️⃣:属性的填充
2内容我们讲述了获取单例的流程,而在这个流程中填充属性是必不可少的,它是完成单例获取的重要环节,比如我们熟知的@Autowired也是在这里完成解析的。
- 进行自动注入之前,spring会提供一个修改bean状态的机会
// 留给开发者扩展用的,必须实现InstantiationAwareBeanPostProcessor接口postProcessAfterInstantiation的方法,设置方法返回false时终止bean填充过程
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
}
上面代码肯定会有个入口的,那么是如何注册的呢,看下面代码
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
beanFactory.addBeanPostProcessor(new AutowiredAnnotationBeanPostProcessor());
注册入口是在初始化容器的时候添加的
- 属性自动注入
我们在配置bean的XML信息的时候有个autowire属性,其中属性值有no,byName, byType, constructor, 五种值分别表示0,1,2,3,默认值为no
①、首先初始化实例的时候如果是在构造函数上注入属性则会走constructor注入类型,严格来讲autowire不一定非得是constructor类型才会走constructor注入
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
由上面代码片段我们能看出走constructor注入的条件有俩个:第一个是标注@Autowired的构造函数,第二个是该bean设置autowire属性为constructor
所以构造函数标注@Autowired也会走constructor注入
②、其次是判断该bean的注入类型是否是byName,byType类型
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// 通过bean名称获取属性值
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// 通过bean类型获取属性值
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
根据上述代码我们可以看到autowireByName、autowireByType函数分别表示byName、byType类型的具体实现。我们先看下byName是如何实现的:
protected void autowireByName(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
// 获取当前bean的属性名称
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
if (containsBean(propertyName)) {
// 根据属性名称递归获取属性值
Object bean = getBean(propertyName);
pvs.add(propertyName, bean);
// 注册该属性
registerDependentBean(propertyName, beanName);
} else {
if (logger.isTraceEnabled()) {
logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
"' by name: no matching bean found");
}
}
}
}
由上面的代码逻辑来看byName是根据遍历属性名称来获取属性值的。接下来我们看一下byType是如何实现的
protected void autowireByType(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
// 对该bean下符合条件的属性进行处理
for (String propertyName : propertyNames) {
try {
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
// Don't try autowiring by type for type Object: never makes sense,
// even if it technically is a unsatisfied, non-simple property.
// 即使Object不满足非简单属性也不要用它作为属性值,因为没意义
if (Object.class != pd.getPropertyType()) {
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
// Do not allow eager init for type matching in case of a prioritized post-processor.
boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered);
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
// 解析依赖(由DefaultListableBeanFactory实现)
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
if (autowiredArgument != null) {
pvs.add(propertyName, autowiredArgument);
}
// 属性是集合时才会执行下面代码
for (String autowiredBeanName : autowiredBeanNames) {
registerDependentBean(autowiredBeanName, beanName);
}
autowiredBeanNames.clear();
}
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
}
}
}
上面代码可以看到Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter); 的赋值操作, 我们进入这个方法看下:
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
// 处理依赖属性是java.util.Optional类型
if (Optional.class == descriptor.getDependencyType()) {
return createOptionalDependency(descriptor, requestingBeanName);
}
// 处理依赖属性是ObjectFactory类型
else if (ObjectFactory.class == descriptor.getDependencyType() ||
ObjectProvider.class == descriptor.getDependencyType()) {
return new DependencyObjectProvider(descriptor, requestingBeanName);
}
// 处理依赖属性是javax.inject.Provider类型
else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
return new Jsr330ProviderFactory().createDependencyProvider(descriptor, requestingBeanName);
}
else {
// 处理器是ContextAnnotationAutowireCandidateResolver返回的result不为空
Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
descriptor, requestingBeanName);
if (result == null) {
// 进一步处理
result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
}
return result;
}
}
针对上述的特殊处理情况在这不做讲解,在处理懒加载问题上也不做过多讲解,我们主要对result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);看代码:
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
try {
Object shortcut = descriptor.resolveShortcut(this);
if (shortcut != null) {
return shortcut;
}
Class<?> type = descriptor.getDependencyType();
// 对属性带有@Value的注解进行解析
// 解析器QualifierAnnotationAutowireCandidateResolver
Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
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());
return (descriptor.getField() != null ?
converter.convertIfNecessary(value, type, descriptor.getField()) :
converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
}
// 解析属性为Array、Map、Collection的类型
Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
if (multipleBeans != null) {
return multipleBeans;
}
// 按照属性类型获取匹配的属性值
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) {
// 如果属性设为不必须依赖(autowireByType默认是不必须, @Autowired默认是必须),则不报错
if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
return descriptor.resolveNotUnique(type, 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 {
// 如果只有一个匹配的情况(也是我们所期望的情况)
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);
}
}
上述代码的执行流程是先判断当前属性是否是@Value注解标识的,如果是则直接返回解析的结果。其次解析属性为Array、Map、Collection
的类型的处理操作Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter)
,如果multipleBeans
为空则解析属性为对象的操作Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor)
,那我们看下这段代码:
protected Map<String, Object> findAutowireCandidates(
@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {
// 这个方法就是根据就是我们所要找的,根据类型查找
String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this, requiredType, true, descriptor.isEager());
Map<String, Object> result = new LinkedHashMap<>(candidateNames.length);
for (Class<?> autowiringType : this.resolvableDependencies.keySet()) {
if (autowiringType.isAssignableFrom(requiredType)) {
Object autowiringValue = this.resolvableDependencies.get(autowiringType);
autowiringValue = AutowireUtils.resolveAutowiringValue(autowiringValue, requiredType);
if (requiredType.isInstance(autowiringValue)) {
result.put(ObjectUtils.identityToString(autowiringValue), autowiringValue);
break;
}
}
}
// 遍历查找的属性名称获取属性值result
for (String candidate : candidateNames) {
if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) {
addCandidateEntry(result, candidate, descriptor, requiredType);
}
}
if (result.isEmpty() && !indicatesMultipleBeans(requiredType)) {
// Consider fallback matches if the first pass failed to find anything...
DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch();
for (String candidate : candidateNames) {
if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor)) {
addCandidateEntry(result, candidate, descriptor, requiredType);
}
}
if (result.isEmpty()) {
// Consider self references as a final pass...
// but in the case of a dependency collection, not the very same bean itself.
for (String candidate : candidateNames) {
if (isSelfReference(beanName, candidate) &&
(!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) &&
isAutowireCandidate(candidate, fallbackDescriptor)) {
addCandidateEntry(result, candidate, descriptor, requiredType);
}
}
}
}
return result;
}
这段代码就是根据属性类型查找属性名称数组,然后遍历此数组根据名称获取属性值。由于我们根据属性类型查找的,所以获取的属性值可能是一个也可能是多个,是一个的情况下则直接返回结果。如果获取多个属性值的话则再根据属性名称进一步匹配,有匹配的就直接返回,没有匹配的则继续判断该属性赋值是否是必须的(@Autowired(required = false)默认是true
),是则抛出异常,否则赋值null
分析了以上代码片段我们得知了autowireByType
函数主要目的是获取符合该属性类型的所有属性值并存放到MutablePropertyValues,最后通过applyPropertyValues(beanName, mbd, bw, pvs);进行setter赋值
,也就是通过autowireByType
赋值的属性必须提供一个setter方法,否则会抛出异常
除了XML配置的形式,还有一种我们常用的注入方式那就是@Autowired
方式,那这种方式是哪里解析的呢,让我们看下代码:
//判断是否注册了BeanPostProcessor后置处理器
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
if (hasInstAwareBpps || needsDepCheck) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
// 必须是继承InstantiationAwareBeanPostProcessor接口的处理器
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 处理器的核心方法
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
实现此方法ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
的实现类有
CommonAnnotationBeanPostProcessor(主要对@Resource注解的处理)、AutowiredAnnotationBeanPostProcessor(主要对@Autowired注解的处理)、 RequiredAnnotationBeanPostProcessor(主要对@Required注解的处理)
接下来我们主要针对AutowiredAnnotationBeanPostProcessor
处理器作讲解,那我们看下该处理器对postProcessPropertyValues方法的处理方式:
public PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException {
// 获取带有@Autowired注解的field、method并封装此对象
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
try {
// 对bean属性进行注入
metadata.inject(bean, beanName, pvs);
}
catch (BeanCreationException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
}
return pvs;
}
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
Collection<InjectedElement> checkedElements = this.checkedElements;
// 所有带@Autowired的属性、方法都在这个集合里面
Collection<InjectedElement> elementsToIterate =
(checkedElements != null ? checkedElements : this.injectedElements);
if (!elementsToIterate.isEmpty()) {
// 对每一个属性、方法进行属性值的填充
for (InjectedElement element : elementsToIterate) {
if (logger.isDebugEnabled()) {
logger.debug("Processing injected element of bean '" + beanName + "': " + element);
}
// 填充的具体实现方法
element.inject(target, beanName, pvs);
}
}
}
我们看一下element.inject()这个方法的实现:
// AutowiredFieldElement(属性的实现方式)
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
// 属性
Field field = (Field) this.member;
Object value;
if (this.cached) {
value = resolvedCachedArgument(beanName, this.cachedFieldValue);
}
else {
// 封装属性的一些属性
DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
desc.setContainingClass(bean.getClass());
Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
Assert.state(beanFactory != null, "No BeanFactory available");
TypeConverter typeConverter = beanFactory.getTypeConverter();
try {
// 此处是不是有些熟悉呢,这里就是autowiredByType函数获取属性值的核心方法了,
// 唯一不同的就是这里是通过属性field.set()填充值的,
// 而autowiredByType里面的desc是通过方法method(setter)实现的。
// 俩种方式都调用resolveDependency函数,此函数是先根据属性的类型查找,如果查到多个则会再根据名称查找(单个属性的情况,如果是属性是集合则直接返回)。
// 不了解的同学可以看上述的byType小节,里面有详细的讲解
value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
}
// ...代码忽略
if (value != null) {
// 看到这我们也许就恍然大悟了,反射赋值
ReflectionUtils.makeAccessible(field);
field.set(bean, value);
}
}
// AutowiredMethodElement(方法的实现方式)
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
if (checkPropertySkipping(pvs)) {
return;
}
Method method = (Method) this.member;
Object[] arguments;
if (this.cached) {
// Shortcut for avoiding synchronization...
arguments = resolveCachedArguments(beanName);
}
else {
// 获取方法参数
Class<?>[] paramTypes = method.getParameterTypes();
arguments = new Object[paramTypes.length];
DependencyDescriptor[] descriptors = new DependencyDescriptor[paramTypes.length];
Set<String> autowiredBeans = new LinkedHashSet<>(paramTypes.length);
Assert.state(beanFactory != null, "No BeanFactory available");
TypeConverter typeConverter = beanFactory.getTypeConverter();
// 对每个参数进行注入
for (int i = 0; i < arguments.length; i++) {
MethodParameter methodParam = new MethodParameter(method, i);
// 这里是方法注入方法
DependencyDescriptor currDesc = new DependencyDescriptor(methodParam, this.required);
currDesc.setContainingClass(bean.getClass());
descriptors[i] = currDesc;
try {
// 上面的field方式注入已经讲解
Object arg = beanFactory.resolveDependency(currDesc, beanName, autowiredBeans, typeConverter);
if (arg == null && !this.required) {
arguments = null;
break;
}
arguments[i] = arg;
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(methodParam), ex);
}
}
// 代码忽略...
if (arguments != null) {
try {
// 方法的反射赋值
ReflectionUtils.makeAccessible(method);
method.invoke(bean, arguments);
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
与autowiredByType
的处理比较@Autowired
注解的处理不同之处在于@Autowired
注解的作用范围其中作用到field、method
俩种类型上面,而autowiredByType需要属性提供setter方法
通过这些源码的讲解,让我懂得的一些代码的设计思想,比如bean的后置处理器,我们可以看到@Autowired、@Resource、@Required
等注解的处理方式都是一个类一个处理方式,都是实现了InstantiationAwareBeanPostProcessor
接口,符合设计模式的原则
3️⃣、属性填充的最后一步
applyPropertyValues(beanName, mbd, bw, pvs);
此函数是填充的最后一步,autowiredByName、autowiredByType都是通过这步骤完成属性填充的(通过setter方式调用)