上一篇Spring源码二十:Bean实例化流程三中,我们主要讨论了单例Bean创建对象的主要方法getSingleton的内部方法createBean,createBean方法中的resolveBeanClase方法与prepareMethodOverrides方法处理了lookup-method属性与repliace-method配置属性。重点讨论了resolveBeforeInstantiation,看了Spring为我们提供的两个扩展方法。最后我们找到了正常创建bena的方法,doCreateBean。
今天开始进入doCreateBean中一探究竟:
doCreateBean
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)throws BeanCreationException {// Instantiate the bean.// 实例化这个beanBeanWrapper instanceWrapper = null;if (mbd.isSingleton()) {// 如果是单例,则从factoryBeanInstanceCache获取一个FactoryBeanWrapper对象,// 默认情况是单且factoryBeanInstanceCache为空,所以instanceWrapper还是 = nullinstanceWrapper = this.factoryBeanInstanceCache.remove(beanName);}// 创建BeanWrapper实例对象:默认情况都是空,所以肯定会走这里if (instanceWrapper == null) {instanceWrapper = createBeanInstance(beanName, mbd, args);}// 获取实例化对象final Object bean = instanceWrapper.getWrappedInstance();// 获取实例化对象类型Class<?> beanType = instanceWrapper.getWrappedClass();if (beanType != NullBean.class) {mbd.resolvedTargetType = beanType;}// Allow post-processors to modify the merged bean definition.// 允许后置处理器修改beanDefinitionsynchronized (mbd.postProcessingLock) {if (!mbd.postProcessed) {try {applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);}catch (Throwable ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,"Post-processing of merged bean definition failed", ex);}mbd.postProcessed = true;}}// Eagerly cache singletons to be able to resolve circular references// even when triggered by lifecycle interfaces like BeanFactoryAware.boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&isSingletonCurrentlyInCreation(beanName));if (earlySingletonExposure) {if (logger.isTraceEnabled()) {logger.trace("Eagerly caching bean '" + beanName +"' to allow for resolving potential circular references");}addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));}// Initialize the bean instance. bean对象的初始化、DI在此出发// 这个exposed的对象,Object exposedObject = bean;try {populateBean(beanName, mbd, instanceWrapper);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) {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 " +"'getBeanNamesForType' 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;}
首先回去BeanFactory的缓存中获取Bean Wrapper对象,默认没有所以肯定会走到createBeanInstance方法中,我们进入方法内部看下。
createBeanInstance
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {// Make sure bean class is actually resolved at this point.// 在此调用resolveBeanClass方法,解析BeanDefinition中的class ,确保现在bean的class已经被解析好了Class<?> beanClass = resolveBeanClass(mbd, beanName);// 这里对class进行校验,主要是反射需要用的到的属性:// 如果类不是public修饰的,并且不能通过反射访问 提前抛出异常if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());}Supplier<?> instanceSupplier = mbd.getInstanceSupplier();if (instanceSupplier != null) {return obtainFromSupplier(instanceSupplier, beanName);}// 如果属性factory-method不为空,则通过配置好的工厂方法来实例化bean// 这里为Spring 提供了通过工厂方法来实例化Beanif (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);}}// Candidate constructors for autowiring?Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {return autowireConstructor(beanName, mbd, ctors, args);}// Preferred constructors for default construction?ctors = mbd.getPreferredConstructors();if (ctors != null) {return autowireConstructor(beanName, mbd, ctors, null);}// No special handling: simply use no-arg constructor.return instantiateBean(beanName, mbd);}
上述代码注释基本上都解释了一遍,咱们简单总结下:
类解析和校验:首先解析bean的类,并进行访问权限校验。这一步确保了后续操作的前提条件都已经满足。
实例供应商检查:如果定义了实例供应商,则通过供应商创建实例。这种方式提供了高度的灵活性,使得实例的创建可以由外部逻辑控制。一般不做扩展,故不做具体分析
工厂方法实例化:如果定义了工厂方法,则通过工厂方法创建实例。工厂方法模式是一种常见的设计模式,能够灵活地创建对象。这块我们等会进去看下。主要还是Spring给我们提供了一种实例化方式,等会举例说明。
构造函数解析和自动装配:解析候选的构造函数并进行自动装配。这种方式适用于需要依赖注入的场景,确保bean的依赖能够被正确地解析和注入。
默认实例化:如果没有特殊的创建需求,则使用无参构造函数进行实例化。这种方式简单直接,适用于大多数情况。
这段代码体现了Spring框架在设计和实现上的许多优秀思想和实践。通过灵活的实例化策略、严格的前置校验、线程安全处理、性能优化以及分层设计,Spring框架能够高效、稳定地处理复杂的bean创建需求。这些设计思想和实践对于任何大型软件系统的设计和实现都有重要的借鉴意义。
工厂方法来实例化Bean
有两种方式来定义,主要是静态方法与普通方法,下面咱们来看下代码:
package org.springframework.factory;import org.springframework.dto.JmUser;/*** @author Jeremy* @version 1.0* @description: 测试FactoryMethod方法* @date 2024/7/10 16:56*/
public class JmUserFactory {public static JmUser getObject(){JmUser jmUser = new JmUser();jmUser.setName("JmUserFactory");jmUser.setAge("1");return jmUser;}public JmUser getJmUser(){JmUser jmUser = new JmUser();jmUser.setName("JmUserFactoryNoStatic");jmUser.setAge("2");return jmUser;}}package org.springframework.dto;/*** @author Jeremy* @version 1.0* @description: 实体类* @date 2024/6/30 03:02*/
public class JmUser {private String name;private String age;private String systemOs;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAge() {return age;}public void setAge(String age) {this.age = age;}
}
<!--factory-method 静态方法--><bean id="jmUserFactory" class="org.springframework.factory.JmUserFactory" factory-method="getObject"></bean><!--factory-method 非静态方法--><bean id="jmUserFactoryNoStatic" class="org.springframework.factory.JmUserFactory" ></bean><bean id="jmCreateUser" factory-bean="jmUserFactoryNoStatic" factory-method="getJmUser" ></bean>
可以看到此时会我们在xml中设置的factory-method方法会set到BeanDefinitionfactoryMethodName中,这里通过getFactoryMethodName方法获取属性值,如果有值则进入factoryMethod方法内部进行实例化。
instantiateUsingFactoryMethod
代码比较长,我大家可以自己去代码里看,我这里就截取核心内容出来。
Spring 框架中用于通过工厂方法实例化 bean 的方法。无论是 bean 类上的静态工厂方法,还是其他工厂 bean 上的方法,都是通过这个方法来处理的。以下是该方法的概述和关键部分的解释:
instantiateUsingFactoryMethod 方法旨在使用指定的工厂方法创建 bean 的新实例。它通过解析适当的方法、准备必要的参数,然后调用该方法来创建 bean。
BeanWrapper 初始化:
BeanWrapperImpl bw = new BeanWrapperImpl();
this.beanFactory.initBeanWrapper(bw);
这里创建了一个 BeanWrapperImpl 实例并进行初始化,BeanWrapper 用于包装 bean 对象并提供对其属性的操作。
获取工厂 bean 和工厂类:
String factoryBeanName = mbd.getFactoryBeanName();
if (factoryBeanName != null) {if (factoryBeanName.equals(beanName)) {throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,"factory-bean reference points back to the same bean definition");}factoryBean = this.beanFactory.getBean(factoryBeanName);if (mbd.isSingleton() && this.beanFactory.containsSingleton(beanName)) {throw new ImplicitlyAppearedSingletonException();}factoryClass = factoryBean.getClass();isStatic = false;
}
else {if (!mbd.hasBeanClass()) {throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,"bean definition declares neither a bean class nor a factory-bean reference");}factoryBean = null;factoryClass = mbd.getBeanClass();isStatic = true;
}
这里获取工厂 bean 和工厂类。如果指定了工厂 bean 名称,则获取该工厂 bean 实例及其类;如果没有指定工厂 bean 名称,则使用 bean 类上的静态工厂方法。
解析工厂方法和参数:
Method factoryMethodToUse = null;
ArgumentsHolder argsHolderToUse = null;
Object[] argsToUse = null;if (explicitArgs != null) {argsToUse = explicitArgs;
}
else {Object[] argsToResolve = null;synchronized (mbd.constructorArgumentLock) {factoryMethodToUse = (Method) mbd.resolvedConstructorOrFactoryMethod;if (factoryMethodToUse != null && mbd.constructorArgumentsResolved) {argsToUse = mbd.resolvedConstructorArguments;if (argsToUse == null) {argsToResolve = mbd.preparedConstructorArguments;}}}if (argsToResolve != null) {argsToUse = resolvePreparedArguments(beanName, mbd, bw, factoryMethodToUse, argsToResolve, true);}
}
这里解析工厂方法和参数。如果有显式参数,则直接使用;否则,从 bean 定义中解析参数。
确定工厂方法:
if (factoryMethodToUse == null || argsToUse == null) {factoryClass = ClassUtils.getUserClass(factoryClass);List<Method> candidates = null;if (mbd.isFactoryMethodUnique) {if (factoryMethodToUse == null) {factoryMethodToUse = mbd.getResolvedFactoryMethod();}if (factoryMethodToUse != null) {candidates = Collections.singletonList(factoryMethodToUse);}}if (candidates == null) {candidates = new ArrayList<>();Method[] rawCandidates = getCandidateMethods(factoryClass, mbd);for (Method candidate : rawCandidates) {if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate)) {candidates.add(candidate);}}}...
}
这里尝试确定具体的工厂方法。首先检查是否有缓存的工厂方法,然后尝试从工厂类的所有方法中找到匹配的方法。
实例化 bean:
bw.setBeanInstance(instantiate(beanName, mbd, factoryBean, factoryMethodToUse, argsToUse));
return bw;
最后,通过解析得到的工厂方法和参数来实例化 bean,并将其包装在 BeanWrapper 中返回。
总结下:就是判断一下当前是通过静态工厂方法,还是通过实例工厂方法来实例化bean的实例。剩下复杂的错都通过反射实例化bean的过程。
小结
今天咱们主要分析里createBeanInstance方法Spring给我们提供给的FactoryMethod方法,举例说明了factoryMethod属性如何使用,同时简单讨论了具体实现逻辑。下一节咱们将进入反射实例化Bean。