本节内容:beanFactory.getBean("user");
@Test
void testGetBean() {
Gun gun = beanFactory.getBean("m416", Gun.class);
log.info("gun={}", gun);
}
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return this.doGetBean(name, requiredType, (Object[])null, false);
}
doGetBean方法整体概述:
/**
* 返回指定bean的一个实例,该实例可以是共享的,也可以是独立的
*/
// eg1:name="m416",requiredType=Gun.class,args=null,typeCheckOnly=false
@SuppressWarnings("unchecked")
protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException {
// 提取真正的beanName(去除‘&’或者将别名name转化为beanName)
String beanName = transformedBeanName(name); // eg1:beanName="m416"
/** 1:尝试根据beanName,从缓存中获得单例对象 */
Object beanInstance, sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) // eg1:sharedInstance=null
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null); // 从bean中获得真正的实例对象
/** 2:缓存中不存在实例,则采取自主创建实例对象 */
else {
// 如果当前bean是正在创建中的原型对象,则直接抛出异常
if (isPrototypeCurrentlyInCreation(beanName)) // eg1:false
throw new BeanCurrentlyInCreationException(beanName);
/** 3:如果存在parentBeanFactory 并且 配置中也没有beanName的配置信息,则尝试从parentBeanFactory中获取实例 */
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // eg1:parentBeanFactory=null
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory)
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(nameToLookup, requiredType, args, typeCheckOnly);
else if (args != null)
return (T) parentBeanFactory.getBean(nameToLookup, args);
else if (requiredType != null)
return parentBeanFactory.getBean(nameToLookup, requiredType);
else
return (T) parentBeanFactory.getBean(nameToLookup);
}
// 如果不执行类型检查,则将beanName保存到alreadyCreated缓存中
if (!typeCheckOnly) // eg1:true
markBeanAsCreated(beanName);
StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate").tag("beanName", name);
try {
if (requiredType != null) // eg1:requiredType=Gun.class
beanCreation.tag("beanType", requiredType::toString);
/** 4:将GenericBeanDefinition转换为RootBeanDefinition,如果是子Bean,则与父类的相关属性进行合并 */
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args); // eg1:mbd=RootBeanDefinition@2607
/** 5:如果存在依赖,那么需要递归每一个依赖的bean并对其进行实例化创建 */
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) { // eg1: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);
try {
getBean(dep); // 创建每一个依赖(dep)的实例Bean
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
/** 6:创建bean的单例实例对象 */
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args); // eg1:return Gun@2334
}
catch (BeansException ex) {
destroySingleton(beanName);
throw ex;
}
});
// eg1:AbstractAutowireCapableBeanFactory#getObjectForBeanInstance
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
/** 7:创建原型对象 */
else if (mbd.isPrototype()) {
Object prototypeInstance;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
/** 8:创建指定scope类型的对象 */
else {
String scopeName = mbd.getScope();
if (!StringUtils.hasLength(scopeName))
throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
Scope scope = this.scopes.get(scopeName);
if (scope == null)
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
try {
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
});
beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new ScopeNotActiveException(beanName, scopeName, ex);
}
}
}
catch (BeansException ex) {
beanCreation.tag("exception", ex.getClass().toString());
beanCreation.tag("message", String.valueOf(ex.getMessage()));
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
finally {
beanCreation.end(); // eg1:DefaultApplicationStartup#end()
}
}
/** 9:检查需要的类型是否符合bean的实际类型,如果不同,则对其进行类型转换 */
return adaptBeanInstance(name, beanInstance, requiredType); // eg1:return Gun@2334
}
factoryBean的用法:
如果在某些情况下,实例化bean的过程比较复杂,如果在中进行配置的话,需要 提供大量的配置信息,这种情况下的配置就失去了灵活性。所以,此时我们可以采取编 码的方式来实例化这个bean,即:通过实现FactoryBean接口,在getObject()方法中去实 现bean的创建过程。那么当Spring发现配置文件中的class属性配置的实现类是 FactoryBean的子类时,就会通过调用FactoryBean#getObject()方法返回bean的实例对象。
// 提取真正的beanName(去除‘&’或者将别名name转化为beanName)
// 提取真正的beanName(去除‘&’或者将别名name转化为beanName)
String beanName = transformedBeanName(name); // eg1:beanName="m416"
/**
* 返回bean名称,必要时去掉工厂引用前缀,并将别名解析为规范名称
*/
// eg1:name="m416"
protected String transformedBeanName(String name) {
return canonicalName(BeanFactoryUtils.transformedBeanName(name));
}
/**
* 返回实际的bean名称,去掉工厂解引用前缀(如果有,也去掉重复的工厂前缀)
*/
// eg1:name="m416"
public static String transformedBeanName(String name) {
Assert.notNull(name, "'name' must not be null");
// 如果不是"&"前缀,则直接返回name即可
if (!name.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) // eg1:true
return name; // eg1:return "m416"
// 去掉所有前缀"&",只返回beanName
return transformedBeanNameCache.computeIfAbsent(name, beanName -> {
do {
beanName = beanName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
}
while (beanName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX));
return beanName;
});
}
/**
* 确定原始名称,将别名解析为规范名称
*/
// eg1:name="m416"
public String canonicalName(String name) {
String canonicalName = name;
String resolvedName;
do {
// eg1:result = {ConcurrentHashMap@2355} size = 5
// "com.muse.springdemo.beanpostprocessor.MuseBeanPostProcessor" -> "com.muse.springdemo.beanpostprocessor.MuseBeanPostProcessor#0"
// "org.springframework.web.servlet.view.InternalResourceViewResolver" -> "org.springframework.web.servlet.view.InternalResourceViewResolver#0"
// "muse" -> "customUser"
// "alias_ent" -> "ent"
// "org.springframework.beans.factory.config.CustomEditorConfigurer" -> "org.springframework.beans.factory.config.CustomEditorConfigurer#0"
/** 从别名中寻找原始名称 */
resolvedName = this.aliasMap.get(canonicalName);
if (resolvedName != null) // eg1:resolvedName=null
canonicalName = resolvedName;
}
while (resolvedName != null);
return canonicalName; // eg1:return "m416"
}
【去除‘&’或者将别名name转化为beanName】的举例:
Computer实体类:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Computer {
private String brand;
private double price;
}
ComputerFactoryBean类:
@Data
public class ComputerFactoryBean implements FactoryBean<Computer> {
private String computerInfo; // 计算机信息
@Override
public Computer getObject() {
if (!StringUtils.hasText(computerInfo)) // eg1:computerInfo="苹果MacPro, 30000"
return null;
String[] args = computerInfo.split(",");
Computer computer = new Computer(args[0], Double.valueOf(args[1]));
return computer;
}
@Override
public Class<?> getObjectType() {
return Computer.class;
}
}
FactoryBean接口:
public interface FactoryBean<T> {
String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType";
@Nullable
T getObject() throws Exception;
@Nullable
Class<?> getObjectType();
default boolean isSingleton() {
return true;
}
}
bean.xml文件:
<!-- factorybean演示 -->
<bean id="computer" class="com.muse.springdemo.factorybean.ComputerFactoryBean">
<property name="computerInfo" value="苹果MacPro, 30000"/>
</bean>
当需要获取Computer实例对象时,通过调用getBean("computer")即可;如果我们想要获 得FactoryBean的实例对象,则可以通过调用getBean("&computer")即可
@Test
void testBeanFactory() {
Computer computer = beanFactory.getBean("computer", Computer.class);
log.info("computer1={}", computer);
ComputerFactoryBean bean = beanFactory.getBean("&computer", ComputerFactoryBean.class);
log.info("computer2={}", bean.getObject());
}
运行结果:
/** 1:尝试根据beanName,从缓存中获得单例对象 */
由于单例在Spring容器中只会被创建一次,即:创建出来的单例实例对象就会被缓存到 singletonObjects中。所以,当要获得某个beanName的实例对象时,会首先尝试从 singletonObjects中加载,如果加载不到,则再尝试从earlySingletonObjects中加载,如 果还是加载不到,则再尝试从singletonFactories中加载对象工厂,然后通过调用其 ObjectFactory#getObject()方法来获得实例对象。
因为在创建单例bean的时候可能会存在依赖注入的情况,所以为了避免循环依赖, Spring创建bean的原则是不等bean创建完成就会将创建bean的ObjectFactory提早曝光加 入到缓存singletonFactories中,如果下一个bean创建时需要依赖上一个bean,则直接使 用ObjectFactory。
获得空对象
// eg1:beanName="m416"
@Override
@Nullable
public Object getSingleton(String beanName) {
return getSingleton(beanName, true);
}
/**
* 返回以给定名称注册的(原始)单例对象。检查已经实例化的单例,也允许对当前创建的单例进行早期引用(解析循环引用)。
* ① 尝试从singletonObjects中获取
* ② 尝试从earlySingletonObjects中获取
* ③ 尝试从singletonFactories中获取
*/
// eg2:beanName="m416",allowEarlyReference=false
// eg1:beanName="m416",allowEarlyReference=true
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
/** 1:尝试先从缓存【singletonObjects】中获取 */
// eg2:singletonObjects.size()=0
// eg1:singletonObjects.size()=0
Object singletonObject = this.singletonObjects.get(beanName);
/** 2:如果缓存中没有,并且当前的bean正在被创建 */
if (singletonObject == null && // eg1:singletonObject=null
isSingletonCurrentlyInCreation(beanName)) { // eg1:false // eg2:true
/** 2-1:再次尝试从缓存【earlySingletonObjects】中获取 */
singletonObject = this.earlySingletonObjects.get(beanName); // eg2:earlySingletonObjects.size()=0
/** 2-2:如果缓存中没有,并且允许早期依赖(allowEarlyReference=true)*/
if (singletonObject == null // eg2:true
&& allowEarlyReference) { // eg2:false
synchronized (this.singletonObjects) {
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null) {
/** 2-3:最后:尝试从缓存【singletonFactories】中获取对象工厂 */
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject(); // 通过对象工厂获得实例对象
this.earlySingletonObjects.put(beanName, singletonObject); // 维护到缓存中
this.singletonFactories.remove(beanName);
}
}
}
}
}
}
return singletonObject; // eg1:return null // eg2:return null
}
于是:
/** 2:缓存中不存在实例,则采取自主创建实例对象 */
// 如果当前bean是正在创建中的原型对象,则直接抛出异常
/**
* 返回指定的原型bean当前是否正在创建中(在当前线程内)
*/
// eg1:beanName="m416"
protected boolean isPrototypeCurrentlyInCreation(String beanName) {
Object curVal = this.prototypesCurrentlyInCreation.get();
return (curVal != null && // eg1:curVal=null
(curVal.equals(beanName) || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName))));
}
/** 3:如果存在parentBeanFactory 并且 配置中也没有beanName的配置信息,则尝试从parentBeanFactory中获取实例 */
/** 3:如果存在parentBeanFactory 并且 配置中也没有beanName的配置信息,则尝试从parentBeanFactory中获取实例 */
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // eg1:parentBeanFactory=null
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory)
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(nameToLookup, requiredType, args, typeCheckOnly);
else if (args != null)
return (T) parentBeanFactory.getBean(nameToLookup, args);
else if (requiredType != null)
return parentBeanFactory.getBean(nameToLookup, requiredType);
else
return (T) parentBeanFactory.getBean(nameToLookup);
}
// 如果不执行类型检查,则将beanName保存到alreadyCreated缓存中
/**
* 将指定的bean标记为已创建(或即将创建)。这允许bean工厂优化其缓存以重复创建指定的bean。
*/
// eg1:beanName="m416"
protected void markBeanAsCreated(String beanName) {
if (!this.alreadyCreated.contains(beanName)) { // eg1:alreadyCreated.size()=0
synchronized (this.mergedBeanDefinitions) {
if (!this.alreadyCreated.contains(beanName)) {
clearMergedBeanDefinition(beanName);
/** 维护到缓存alreadyCreated中 */
this.alreadyCreated.add(beanName);
}
}
}
}
/** 4:将GenericBeanDefinition转换为RootBeanDefinition,如果是子Bean,则与父类的相关属性进行合并 */
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args); // eg1:mbd=RootBeanDefinition@2607
/**
* 返回合并的RootBeanDefinition,如果指定的bean对应于子bean定义,则遍历父bean定义。
*/
// eg1:beanName="m416"
protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName); // eg1:mergedBeanDefinitions.size()=0
if (mbd != null && !mbd.stale) // eg1:mbd=null
return mbd;
return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
}
/**
* 如果给定bean的定义是子bean定义,通过与父bean合并,返回给定顶级bean的RootBeanDefinition。
*/
// eg1:beanName="m416", bd=GenericBeanDefinition@2525
protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd) throws BeanDefinitionStoreException {
return getMergedBeanDefinition(beanName, bd, null);
}
/**
* 如果给定bean的定义是子bean定义,通过与父bean合并,返回给定顶级bean的RootBeanDefinition。
*/
// eg1:beanName="m416",bd=GenericBeanDefinition@2525,containingBd=null
protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
throws BeanDefinitionStoreException {
synchronized (this.mergedBeanDefinitions) {
RootBeanDefinition mbd = null;
RootBeanDefinition previous = null;
if (containingBd == null) // eg1:containingBd=null
mbd = this.mergedBeanDefinitions.get(beanName); // eg1:mergedBeanDefinitions.size()=0
if (mbd == null || mbd.stale) { // eg1:mbd=null
previous = mbd;
if (bd.getParentName() == null) { // eg1:true
if (bd instanceof RootBeanDefinition) // eg1:false
mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
else
mbd = new RootBeanDefinition(bd);
}
else {
BeanDefinition pbd;
try {
String parentBeanName = transformedBeanName(bd.getParentName());
if (!beanName.equals(parentBeanName))
pbd = getMergedBeanDefinition(parentBeanName);
else {
BeanFactory parent = getParentBeanFactory();
if (parent instanceof ConfigurableBeanFactory)
pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);
else
throw new NoSuchBeanDefinitionException(parentBeanName,
"Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
"': cannot be resolved without a ConfigurableBeanFactory parent");
}
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
"Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
}
mbd = new RootBeanDefinition(pbd);
mbd.overrideFrom(bd);
}
if (!StringUtils.hasLength(mbd.getScope())) // eg1:mbd.getScope()=""
mbd.setScope(SCOPE_SINGLETON);
if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) // eg1:containingBd=null
mbd.setScope(containingBd.getScope());
if (containingBd == null && isCacheBeanMetadata()) // eg1:true
this.mergedBeanDefinitions.put(beanName, mbd);
}
if (previous != null) // eg1:previous=null
copyRelevantMergedBeanDefinitionCaches(previous, mbd);
return mbd;
}
}
/**
* 检查给定的合并bean定义,可能会抛出验证异常。
*/
// eg1:beanName="m416", args=null
protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, @Nullable Object[] args)
throws BeanDefinitionStoreException {
if (mbd.isAbstract()) // eg1:false
throw new BeanIsAbstractException(beanName);
}
/** 5:如果存在依赖,那么需要递归每一个依赖的bean并对其进行实例化创建 */
/** 5:如果存在依赖,那么需要递归每一个依赖的bean并对其进行实例化创建 */
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) { // eg1: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);
try {
getBean(dep); // 创建每一个依赖(dep)的实例Bean
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
/**
* 为给定的bean注册一个依赖的bean,在给定的bean被销毁之前被销毁。
*
* @param beanName :被依赖的bean的名称(City、Road、Area)
* @param dependentBeanName: 依赖的bean的名称(Address)
*/
public void registerDependentBean(String beanName, String dependentBeanName) {
String canonicalName = canonicalName(beanName); // 确定原始名称,将别名解析为规范名称
/** 2:维护dependentBeanMap缓存,{key=beanName, value=依赖了这个bean的所有其他beanName的集合} */
synchronized (this.dependentBeanMap) {
Set<String> dependentBeans = this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>(8));
if (!dependentBeans.add(dependentBeanName)) return;
}
/** 2:维护dependenciesForBeanMap缓存,{key=beanName, value=该bean依赖的所有其他beanName集合} */
synchronized (this.dependenciesForBeanMap) {
Set<String> dependenciesForBean = this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet<>(8));
dependenciesForBean.add(canonicalName);
}
}
/** 6:创建bean的单例实例对象 */(重要)
getSingleton(beanName, singletonFactory)获得单例对象
getSingleton(beanName)的主要作用就是从 缓存中获取单例对象。那么下面我们要介绍的方法是步骤6中的getSingleton(beanName, singletonFactory),是针对于缓存中并不存在单例bean的时候的处理流程。
首先,尝试从缓存singletonObjects中获取bean实例,如果获取到了,就执行return返回 该实例对象。其次,如果没有从缓存中获取到bean实例,则通过调用ObjectFactory的 getObject()方法获取bean实例。 由于ObjectFactory是接口,所以getObject()方法需要 单独实现。最后,将实例对象return返回即可。
/** 6:创建bean的单例实例对象 */
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args); // eg1:return Gun@2334
}
catch (BeansException ex) {
destroySingleton(beanName);
throw ex;
}
});
// eg1:AbstractAutowireCapableBeanFactory#getObjectForBeanInstance
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
/**
* 返回以给定名称注册的(原始)单例对象,如果还没有注册,则创建并注册一个新的单例对象。
*/
// eg1:beanName="m416"
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
/** 1:尝试从缓存中获取bean实例 */
Object singletonObject = this.singletonObjects.get(beanName); // eg1:singletonObjects.size()=0
if (singletonObject == null) { // eg1:singletonObject=null
if (this.singletonsCurrentlyInDestruction) // eg1:false
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!)");
/** 2:将beanName加入到缓存singletonsCurrentlyInCreation中 */
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null); // eg1:suppressedExceptions=null
if (recordSuppressedExceptions) // eg1:true
this.suppressedExceptions = new LinkedHashSet<>();
try {
/** 3:尝试调用ObjectFactory#getObject()方法,获取bean实例 */
singletonObject = singletonFactory.getObject(); // eg1:singletonObject=Gun@2334
newSingleton = true;
}
catch (IllegalStateException ex) {
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) throw ex;
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions)
for (Exception suppressedException : this.suppressedExceptions)
ex.addRelatedCause(suppressedException);
throw ex;
}
finally {
if (recordSuppressedExceptions) // eg1:true
this.suppressedExceptions = null;
/** 4:将beanName从singletonsCurrentlyInCreation中移除掉 */
afterSingletonCreation(beanName);
}
/**
* 5: 添加缓存:singletonObjects 和 registeredSingletons
* 移除缓存:singletonFactories 和 earlySingletonObjects
*/
if (newSingleton) // eg1:true
addSingleton(beanName, singletonObject);
}
return singletonObject; // eg1:return Gun@2334
}
}
第3步中,singletonFactory.getObject()方法很重要,singletonFactory是getSingleton()传进来的参数,该参数的创建:
createBean 创 建 bean 实例对象
getSingleton(beanName, singletonFactory)方法源码部分提到了singletonFactory,它是ObjectFactory类型的,它是一个接口,并且这个接口只提供 了一个方法getObject(),需要单独实现这个方法,来完成bean实例对象的创建,那么具 体创建代码在哪个地方呢,即上图中红框的createBean(beanName, mbd, args)方法
/**
* 这个类的主要方法:创建bean实例,填充bean实例,应用后处理器,等等。
*/
// eg1:beanName="m416",args=null
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
RootBeanDefinition mbdToUse = mbd;
/** 1:根据class属性或className来获得Class实例对象,如果mbd中没有设置beanClass,则创建新的mbdToUse,设置beanClass */
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && // eg1:resolvedClass=Gun.class
!mbd.hasBeanClass() && // eg1:mbd.hasBeanClass()=true
mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
/** 2:验证和准备覆盖的方法(MethodOverrides)*/
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", ex);
}
/** 3:给BeanPostProcessors一个机会,来返回一个替代真正实例的代理对象,并直接return返回 */
try {
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) // eg1:bean=null
return bean;
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex);
}
/** 4:真正开始创建bean实例对象 */
try {
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
return beanInstance; // eg1:return Gun@2334
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
循环依赖——构造器循环依赖
构造器循环依赖:
setter循环依赖:
原型类型循环依赖:
步骤1:根据class属性或className来获得Class实例对象,如果mbd中没有设置beanClass,则创建新的mbdToUse,设置beanClass
resolveBeanClass:
/**
* 解析指定bean定义的bean类,将bean类名解析为类引用(如有必要),并将解析后的类存储在bean定义中以供进一步使用。
*/
// eg1:beanName="m416", typesToMatch.length=0
@Nullable
protected Class<?> resolveBeanClass(RootBeanDefinition mbd, String beanName, Class<?>... typesToMatch) throws CannotLoadBeanClassException {
try {
/** 1:如果mbd中配置了BeanClass,则获取后直接返回 */
if (mbd.hasBeanClass()) // eg1:false
return mbd.getBeanClass();
if (System.getSecurityManager() != null) // eg1:false
return AccessController.doPrivileged((PrivilegedExceptionAction<Class<?>>)
() -> doResolveBeanClass(mbd, typesToMatch), getAccessControlContext());
/** 2:解析bean的类型Class */
else
return doResolveBeanClass(mbd, typesToMatch); // eg1:return Gun.class
}
}
/**
* 解析bean的类型Class
*/
// eg1:typesToMatch.length=0
@Nullable
private Class<?> doResolveBeanClass(RootBeanDefinition mbd, Class<?>... typesToMatch) throws ClassNotFoundException {
ClassLoader beanClassLoader = getBeanClassLoader();
ClassLoader dynamicLoader = beanClassLoader;
boolean freshResolve = false;
if (!ObjectUtils.isEmpty(typesToMatch)) { // eg1:false
ClassLoader tempClassLoader = getTempClassLoader();
if (tempClassLoader != null) {
dynamicLoader = tempClassLoader;
freshResolve = true;
if (tempClassLoader instanceof DecoratingClassLoader) {
DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader;
for (Class<?> typeToMatch : typesToMatch)
dcl.excludeClass(typeToMatch.getName());
}
}
}
/** 1:如果可以获得className */
String className = mbd.getBeanClassName();
if (className != null) { // eg1:className="com.muse.springdemo.entity.Gun"
/** 1-1:针对mdb(可能将其作为表达式进行解析),解析出className或者Class实例 */
Object evaluated = evaluateBeanDefinitionString(className, mbd);
/** 1-2:如果通过表达式解析出来的evaluated与className不同,则以evaluated为准 */
if (!className.equals(evaluated)) { // eg1:evaluated="com.muse.springdemo.entity.Gun"
if (evaluated instanceof Class)
return (Class<?>) evaluated; // 返回通过mbd解析出来的evaluated实例
else if (evaluated instanceof String) {
className = (String) evaluated;
freshResolve = true;
}
else throw new IllegalStateException("Invalid class name expression result: " + evaluated);
}
/** 1-2 如果freshResolve是true并且解析出来的className是字符串类型,则转换为Class对象类型并返回 */
if (freshResolve) { // eg1:false
if (dynamicLoader != null) {
try {
return dynamicLoader.loadClass(className); // 返回通过mbd解析出来的evaluated的Class实例
}
catch (ClassNotFoundException ex) {}
}
return ClassUtils.forName(className, dynamicLoader);
}
}
/** 否则,以mbd.getBeanClassName()为准,来创建Class实例对象 */
return mbd.resolveBeanClass(beanClassLoader); // eg1:return Gun.class
}
/**
* 计算bean定义中包含的给定字符串,可能将其解析为表达式。
*/
// eg2:value="M416"
// eg1:value="com.muse.springdemo.entity.Gun"
@Nullable
protected Object evaluateBeanDefinitionString(@Nullable String value, @Nullable BeanDefinition beanDefinition) {
// 如果没有配置bean的表达式解析器,则直接返回
if (this.beanExpressionResolver == null) // eg1:beanExpressionResolver=null // eg2:beanExpressionResolver=null
return value; // eg1:return "com.muse.springdemo.entity.Gun" // eg2:return "M416"
Scope scope = null;
if (beanDefinition != null) {
String scopeName = beanDefinition.getScope();
if (scopeName != null) scope = getRegisteredScope(scopeName);
}
// 表达式解析操作
return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope));
}
/**
* 确定被包装bean的类,如果需要,从指定的类名解析它。还将在调用已经解析的bean类时从其名称重新加载指定的类。
*/
@Nullable
public Class<?> resolveBeanClass(@Nullable ClassLoader classLoader) throws ClassNotFoundException {
String className = getBeanClassName(); // eg1:className="com.muse.springdemo.entity.Gun"
if (className == null) return null;
Class<?> resolvedClass = ClassUtils.forName(className, classLoader); // 转成Class类型
this.beanClass = resolvedClass;
return resolvedClass; // eg1:return Gun.class
}
步骤2:验证和准备覆盖的方法(MethodOverrides)mbdToUse.prepareMethodOverrides();
/**
* 验证并准备为该bean定义的方法覆盖。检查是否存在指定名称的方法。
*/
public void prepareMethodOverrides() throws BeanDefinitionValidationException {
// 检查查找方法是否存在,并确定它们的重载状态
if (hasMethodOverrides())
getMethodOverrides().getOverrides().forEach(this::prepareMethodOverride);
}
/**
* 验证并准备给定的方法覆盖。检查指定名称的方法是否存在,如果没有找到,则将其标记为未重载。
*/
protected void prepareMethodOverride(MethodOverride mo) throws BeanDefinitionValidationException {
// 获得指定类中某个方法名称被定义的方法个数
int count = ClassUtils.getMethodCountForName(getBeanClass(), mo.getMethodName());
if (count == 0)
throw new BeanDefinitionValidationException("Invalid method override: no method with name '" + mo.getMethodName() + "' on class [" + getBeanClassName() + "]");
else if (count == 1)
mo.setOverloaded(false); // 将重写标记为未重载
}
步骤3:给BeanPostProcessors一个机会,来返回一个替代真正实例的代理对象,并直接return返回 resolveBeforeInstantiation(beanName, mbdToUse);
/**
* 应用前实例化(before-instantiation)后处理器(post-processors),解析指定bean是否存在前实例化(before-instantiation)快捷方式
*/
// eg1:beanName="m416"
@Nullable
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) { // eg1:mbd.beforeInstantiationResolved=null
/** 1:调用前置和后置处理器 */
if (!mbd.isSynthetic() && // eg1:mbd.isSynthetic()=false
hasInstantiationAwareBeanPostProcessors()) { // eg1:false
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
/** 1-1:调用InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation方法 */
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null)
/** 1-2:调用BeanPostProcessor#postProcessAfterInitialization方法 */
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
/** 2:设置是否执行了beforeInstantiation的解析操作 */
mbd.beforeInstantiationResolved = (bean != null);
}
return bean; // eg1:bean=null
}
1-1调用:
/**
* 将InstantiationAwareBeanPostProcessors应用到指定的bean定义上(通过类和名称),调用它们的postProcessBeforeInstantiation方法。
* 任何返回的对象都将被用作bean,而不是实际实例化目标bean。从后处理程序返回的null值将导致目标bean被实例化。
*/
@Nullable
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
Object result = bp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) return result;
}
return null;
}
1-2调用:
/**
* 遍历调用Bean后置处理器列表postProcessAfterInitialization方法
*/
// eg1:existingBean=Gun@2334,beanName="m416"
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
Object result = existingBean;
/** 调用所有BeanPostProcessor的postProcessAfterInitialization方法 */
for (BeanPostProcessor processor : getBeanPostProcessors()) { // eg1:getBeanPostProcessors().size()=0
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) return result;
result = current;
}
return result; // eg1:return Gun@2334
}
步骤4:真正开始创建bean实例对象(绝大部分通过这里创建)
会发现这么一个规律,就 是:一个真正干活的函数,大多是以do开头命名的。那么,先来从整体上了解一下 doCreateBean方法处理的具体步骤:
① 调用createBeanInstance方法,创建BeanWrapper实例对象instanceWrapper
② 调用所有配置了MergedBeanDefinitionPostProcessor实现类的 postProcessMergedBeanDefinition方法
③ 针对“正在创建”的“允许循环依赖”的“单例“执行【提前曝光getEarlyBeanReference】
④ 调用populateBean方法,对bean进行填充操作,将各个属性值进行注入
⑤ 调用initializeBean方法,调用初始化方法,例如:init-method
⑥ 针对需要执行“提前曝光”的单例
⑦ 如果配置了destroy-method,这里需要注册以便于在销毁时候进行调用 registerDisposableBeanIfNecessary
doCreateBean:
/**
* 实际创建指定的bean。在这一点上已经进行了预创建处理,例如检查{@code postProcessBeforeInstantiation}回调。
* 区分默认bean实例化、使用工厂方法和自动装配构造函数。
*/
// eg1:beanName="m416",args=null
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
/** 1:获取/创建BeanWrapper实例对象instanceWrapper */
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) // eg1:true
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
if (instanceWrapper == null) // eg1:true
instanceWrapper = createBeanInstance(beanName, mbd, args);
/** 2:调用所有配置了MergedBeanDefinitionPostProcessor实现类的postProcessMergedBeanDefinition方法 */
Object bean = instanceWrapper.getWrappedInstance(); // eg1:bean=Gun@2935
Class<?> beanType = instanceWrapper.getWrappedClass(); // eg1:beanType=Gun.class
if (beanType != NullBean.class) // eg1:true
mbd.resolvedTargetType = beanType;
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) { // eg1:true
try {
// eg1:MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); // 允许后处理器修改合并的bean定义
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
/** 3:针对【单例】的【允许循环依赖】的【正在创建】的执行提前曝光 */
boolean earlySingletonExposure = (mbd.isSingleton() && // eg1:true
this.allowCircularReferences && // eg1:true
isSingletonCurrentlyInCreation(beanName)); // eg1:true
if (earlySingletonExposure) // eg1:true
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
Object exposedObject = bean;
try {
/** 4:对bean进行填充操作,将各个属性值进行注入 */
populateBean(beanName, mbd, instanceWrapper);
/** 5:调用初始化方法,例如: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);
}
/** 6:针对需要执行【提前曝光】的单例 */
if (earlySingletonExposure) { // eg1:true
Object earlySingletonReference = getSingleton(beanName, false); // eg1:请见getSingleton方法内的"eg2"标识
if (earlySingletonReference != null) { // eg1: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);
// 因为bean创建后,它所依赖的bean一定创建了,那么不为空则表示所依赖的bean没有全部创建完,即:存在循环依赖
if (!actualDependentBeans.isEmpty()) throw new BeanCurrentlyInCreationException(beanName,"...");
}
}
}
/** 7:如果配置了destroy-method,这里需要注册以便于在销毁时候进行调用 */
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject; // eg1:return Gun@2334
}
1:获取/创建BeanWrapper实例对象instanceWrapper:
createBeanInstance(beanName, mbd, args):
/**
* 使用适当的实例化策略:工厂方法、构造函数自动装配或简单实例化,为指定的bean创建一个新实例。
*/
// eg1:beanName="m416",args=null
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
/** 1:解析beanClass */
Class<?> beanClass = resolveBeanClass(mbd, beanName);
if (beanClass != null && // eg1:beanClass=Gun.class
!Modifier.isPublic(beanClass.getModifiers()) && // eg1:Modifier.isPublic(beanClass.getModifiers())=true
!mbd.isNonPublicAccessAllowed())
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
/** 2:如果配置了instanceSupplier,则通过调用Supplier#get()方法来创建bean的实例,并封装为BeanWrapper实例 */
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) // eg1:instanceSupplier=null
return obtainFromSupplier(instanceSupplier, beanName);
/** 3:如果配置了factoryMethodName或者配置文件中存在factory-method,则使用工厂方法创建bean的实例 */
if (mbd.getFactoryMethodName() != null) // eg1:mbd.getFactoryMethodName()=null
return instantiateUsingFactoryMethod(beanName, mbd, args);
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) { // eg1:args=null
synchronized (mbd.constructorArgumentLock) {
// 一个类有多个构造函数,每个构造函数有不同的参数,所以调用前需要先根据参数锁定构造函数或者对应的工厂方法
if (mbd.resolvedConstructorOrFactoryMethod != null) { // eg1:false
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
/** 4:如果已经解析过(resolved=true),那么就使用解析好的构造函数方法,不需要再次锁定 */
if (resolved) { // eg1:false
if (autowireNecessary)
return autowireConstructor(beanName, mbd, null, null);
else
return instantiateBean(beanName, mbd);
}
/** 5:如果没解析过,那么尝试利用SmartInstantiationAwareBeanPostProcessor的实现类获得构造函数列表 */
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || // eg1:ctors=null
mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR || // eg1:mbd.getResolvedAutowireMode()=AUTOWIRE_NO
mbd.hasConstructorArgumentValues() || // eg1:false
!ObjectUtils.isEmpty(args)) // eg1:args=null
return autowireConstructor(beanName, mbd, ctors, args);
/** 6:尝试从BeanDefinition中获取默认构造的首选构造函数 */
ctors = mbd.getPreferredConstructors();
if (ctors != null) // eg1:ctors=null
return autowireConstructor(beanName, mbd, ctors, null);
/** 7:如果以上都不行,则使用默认构造函数构造bean实例 */
return instantiateBean(beanName, mbd);
}
从步骤4/5/6/7可以看出最重要的两个方法:
autowireConstructor(beanName, mbd, null, null) 和 instantiateBean(beanName, mbd)
前边的1-3步骤是为4-7步骤做准备工作:
步骤1会直接返回beanClass:
/**
* 解析指定bean定义的bean类,将bean类名解析为类引用(如有必要),并将解析后的类存储在bean定义中以供进一步使用。
*/
// eg1:beanName="m416", typesToMatch.length=0
@Nullable
protected Class<?> resolveBeanClass(RootBeanDefinition mbd, String beanName, Class<?>... typesToMatch) throws CannotLoadBeanClassException {
try {
/** 1:如果mbd中配置了BeanClass,则获取后直接返回 */
if (mbd.hasBeanClass()) // eg1:true
return mbd.getBeanClass();
……………………
}
步骤2因为没有配置instanceSupplier,这部分的代码不走。
步骤3因为没有配置factoryMethodName,这部分代码不走。
步骤4因为resolved为false,也不走
步骤5:(也不走)
/**
* 检查所有已注册的SmartInstantiationAwareBeanPostProcessors,确定为给定bean使用的候选构造函数。
*/
// eg1:beanClass=Gun.class,beanName="m416"
@Nullable
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
throws BeansException {
if (beanClass != null && // eg1:true
hasInstantiationAwareBeanPostProcessors()) { // eg1:false
/** 调用所有SmartInstantiationAwareBeanPostProcessor类的determineCandidateConstructors方法 */
for (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) {
Constructor<?>[] ctors = bp.determineCandidateConstructors(beanClass, beanName);
if (ctors != null)
return ctors;
}
}
return null; // eg1:null
}
步骤6:也不走
最后执行的是步骤7的instantiateBean(beanName, mbd)
在createBeanInstance方法的代码中,主要负责创建bean的相关方法有两个,即分别是:
autowireConstructor(beanName, mbd, null, null) 和 instantiateBean(beanName, mbd)
autowireConstructor(beanName, mbd, null, null) :有 参 数 的 实 例 化 构 造
关于autowireConstructor方法的处理逻辑如下所示:
① 确定构造函数方法的入参参数argsToUse:
根据explicitArgs参数进行判断
尝试从mbd中获取
尝试从配置文件中获取
② 确定待调用的构造函数constructorToUse
③ 根据确定的构造函数转换对应的参数类型
④ 构造函数不确定性的验证
⑤ 根据实例化策略类中的instantiate(mbd, beanName, this)方法以及 constructorToUse和argsToUse来实例化bean,并封装到BeanWrapper中。
/**
* “自动构造函数”(按类型指定构造函数参数)行为。
* 如果指定了显式的构造函数参数值,也适用于此,将所有剩余的参数与bean工厂的bean匹配。
* 这对应于构造函数注入:在这种模式下,Spring bean工厂能够托管期望基于构造函数的依赖解析的组件。
*/
protected BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] ctors,
@Nullable Object[] explicitArgs) {
return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
}
/**
* “自动构造函数”(按类型指定构造函数参数)行为。
* 如果指定了显式的构造函数参数值,也适用于此,将所有剩余的参数与bean工厂的bean匹配。
* 这对应于构造函数注入:在这种模式下,Spring bean工厂能够托管期望基于构造函数的依赖解析的组件。
*/
public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] chosenCtors,
@Nullable Object[] explicitArgs) {
BeanWrapperImpl bw = new BeanWrapperImpl();
this.beanFactory.initBeanWrapper(bw); // 初始化BeanWrapper(前面看过了)
Constructor<?> constructorToUse = null;
ArgumentsHolder argsHolderToUse = null;
/**
* 尝试获得构造函数(constructorToUse)和方法入参(argsToUse)
*/
Object[] argsToUse = null;
/** 1-1:如果指定了显式的方法入参explicitArgs,则直接作为构造函数的入参(argsToUse) */
if (explicitArgs != null) argsToUse = explicitArgs;
/** 1-2:如果没有指定explicitArgs,则尝试从mbd中获取构造函数入参argsToUse和构造函数constructorToUse */
else {
Object[] argsToResolve = null;
synchronized (mbd.constructorArgumentLock) {
/** 1-2-1:尝试获得配置中定义的构造函数 */
constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
if (constructorToUse != null && mbd.constructorArgumentsResolved) {
/** 1-2-2:尝试获得构造函数的入参 */
argsToUse = mbd.resolvedConstructorArguments;
if (argsToUse == null)
argsToResolve = mbd.preparedConstructorArguments;
}
}
/** 1-2-3:如果构造函数的入参不为空,则执行参数类型转换。假设构造函数为A(int, int),可以通过如下方法将入参的("1", "1")转换为(1, 1) */
if (argsToResolve != null)
argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve);
}
/** 2:如果constructorToUse和argsToUse没有全部解析出来,则尝试从配置文件中解析获取 */
if (constructorToUse == null || argsToUse == null) {
Constructor<?>[] candidates = chosenCtors;
/** 2-1:如果入参chosenCtors为空,则获取bean中所有的构造方法作为“候选”构造方法 */
if (candidates == null) {
Class<?> beanClass = mbd.getBeanClass();
try {
// 获得类beanClass定义的所有构造函数,并保存到candidates中
candidates = (mbd.isNonPublicAccessAllowed() ? beanClass.getDeclaredConstructors() : beanClass.getConstructors());
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Resolution of declared constructors on bean Class [" + beanClass.getName() +
"] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
}
}
/** 2-2:如果类中只有1个无参的构造函数,则创建bean的实例对象并且return */
if (candidates.length == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {
Constructor<?> uniqueCandidate = candidates[0];
if (uniqueCandidate.getParameterCount() == 0) {
synchronized (mbd.constructorArgumentLock) {
mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
mbd.constructorArgumentsResolved = true;
mbd.resolvedConstructorArguments = EMPTY_ARGS;
}
// 调用instantiate方法,创建实例对象,并返回
bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
return bw;
}
}
/** 2-3:如果chosenCtors不为空,或者配置了autowire="constructor",则采取"贪婪模式"进行构造函数匹配 */
boolean autowiring = (chosenCtors != null || mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
ConstructorArgumentValues resolvedValues = null;
/** 2-4:尝试解析构造函数入参个数(minNrOfArgs)*/
int minNrOfArgs;
if (explicitArgs != null)
minNrOfArgs = explicitArgs.length;
else {
ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues(); // 提取配置文件中配置的构造函数参数
resolvedValues = new ConstructorArgumentValues(); // 用于承载解析后的构造函数参数的值
minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues); // 解析参数个数
}
/** 2-5:对构造函数执行排序操作,其中:public构造函数优先且按照参数数量从多到少降序排列,然后是非public构造函数参数数量降序排列 */
AutowireUtils.sortConstructors(candidates);
int minTypeDiffWeight = Integer.MAX_VALUE;
Set<Constructor<?>> ambiguousConstructors = null;
Deque<UnsatisfiedDependencyException> causes = null;
/** 2-6:遍历所有构造函数,对每个构造函数进行参数匹配操作 */
for (Constructor<?> candidate : candidates) {
int parameterCount = candidate.getParameterCount(); // 获得构造函数参数个数
// 如果显示指定了构造函数constructorToUse,并且使用参数的数量大于当前构造函数的参数数量,则表示该构造函数符合匹配条件,直接返回
if (constructorToUse != null && argsToUse != null && argsToUse.length > parameterCount) break;
// 如果当前构造函数的参数数量小于指定的最小值,直接排除
if (parameterCount < minNrOfArgs) continue;
// 创建构造函数的"参数持有者(ArgumentsHolder)"实例对象argsHolder
ArgumentsHolder argsHolder;
Class<?>[] paramTypes = candidate.getParameterTypes(); // 获得构造函数的入参类型集合
if (resolvedValues != null) { // 只有当explicitArgs等于null时,resolvedValues才满足不为空
try {
// 获得@ConstructorProperties({"x", "y"})注解里配置的参数名称
String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, parameterCount);
if (paramNames == null) {
// 从BeanFactory中获得配置的ParameterNameDiscoverer实现类
ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
// 获得构造函数的入参名称
if (pnd != null) paramNames = pnd.getParameterNames(candidate);
}
// 根据【paramTypes】和【paramNames】创建参数持有者ArgumentsHolder
argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1);
}
catch (UnsatisfiedDependencyException ex) {
if (causes == null) causes = new ArrayDeque<>(1);
causes.add(ex);
continue;
}
}
else {
if (parameterCount != explicitArgs.length) continue;
argsHolder = new ArgumentsHolder(explicitArgs);
}
/** 探测是否有不确定性的构造函数存在,例如:不同构造函数的参数为父子关系 */
int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
// 如果它代表着当前最接近的匹配,则选择作为构造函数
if (typeDiffWeight < minTypeDiffWeight) {
constructorToUse = candidate;
argsHolderToUse = argsHolder;
argsToUse = argsHolder.arguments;
minTypeDiffWeight = typeDiffWeight;
ambiguousConstructors = null;
}
else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
if (ambiguousConstructors == null) {
ambiguousConstructors = new LinkedHashSet<>();
ambiguousConstructors.add(constructorToUse);
}
ambiguousConstructors.add(candidate);
}
}
if (constructorToUse == null) {
if (causes != null) {
UnsatisfiedDependencyException ex = causes.removeLast();
for (Exception cause : causes) this.beanFactory.onSuppressedException(cause);
throw ex;
}
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Could not resolve matching constructor " +
"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
}
else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Ambiguous constructor matches found in bean '" + beanName + "' " +
"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " +
ambiguousConstructors);
}
// 将解析的构造函数加入到缓存中
if (explicitArgs == null && argsHolderToUse != null) argsHolderToUse.storeCache(mbd, constructorToUse);
}
Assert.state(argsToUse != null, "Unresolved constructor arguments");
/** 3:通过constructorToUse和argsToUse创建bean的实例对象,并存储到BeanWrapper中 */
bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
return bw;
}
instantiateBean(beanName, mbd) 无 参 数 的 实 例 化 构 造
上面介绍了带参数的构造方法解析,下面针对不带参数的构造函数的实例化过程进行解析操作。通过解析instantiateBean方法源码之后会发现,主要只有两个操作:
① 通过实例化策略类的instantiate方法创建bean实例对象。
② 将创建的bean实例封装为BeanWrapper对象。
/**
* 使用默认构造函数实例化给定bean
*/
// eg1:beanName="m416"
protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
try {
/** 1:创建bean的实例对象 */
Object beanInstance;
if (System.getSecurityManager() != null) // eg1:false
beanInstance = AccessController.doPrivileged(
(PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this),
getAccessControlContext());
else
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this); // 创建bean实例对象
/** 2:将bean实例对象封装为BeanWrapper对象 */
BeanWrapper bw = new BeanWrapperImpl(beanInstance); // eg1:beanInstance=Gun@2935
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}
1、i n s t a n t i a t e 创 建 b e a n 实 例 对 象
在instantiate方法中,是用来创建bean实例对象的,其中包含两个判断逻辑:
① 如果没有配置lookup-method或replace-method,则直接使用反射创建bean的实例 对象即可
② 否则,需要使用cglib创建代理对象,将动态方法织入到bean的实例对象中
/**
* 创建bean实例对象
*/
// eg1:beanName="m416"
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
/** 1:如果没有配置lookup-method或replace-method,则直接使用反射创建bean的实例对象即可 */
if (!bd.hasMethodOverrides()) { // eg1:bd.hasMethodOverrides()=false
Constructor<?> constructorToUse;
synchronized (bd.constructorArgumentLock) {
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
if (constructorToUse == null) { // eg1:constructorToUse=null
final Class<?> clazz = bd.getBeanClass();
if (clazz.isInterface()) // eg1:clazz=Gun.class
throw new BeanInstantiationException(clazz, "Specified class is an interface");
try {
if (System.getSecurityManager() != null) // eg1:false
constructorToUse = AccessController.doPrivileged((PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
else
constructorToUse = clazz.getDeclaredConstructor();
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Throwable ex) {throw new BeanInstantiationException(clazz, "No default constructor found", ex);}
}
}
// 通过反射构造bean实例对象
return BeanUtils.instantiateClass(constructorToUse); // return Gun@2935
}
/** 2:否则,需要使用cglib创建代理对象,将动态方法织入到bean的实例对象中 */
else return instantiateWithMethodInjection(bd, beanName, owner);
}
2、将bean实例对象封装为BeanWrapper对象
/**
* 用该工厂注册的自定义编辑器初始化给定的BeanWrapper。用于创建和填充bean实例的beanwrapper。
* 默认的实现委托给{@link #registerCustomEditors}。可以在子类中重写。
*/
protected void initBeanWrapper(BeanWrapper bw) {
bw.setConversionService(getConversionService()); // eg1:getConversionService()=null
/** 注册自定义编辑器 */
registerCustomEditors(bw);
}
/**
* 用已经注册到这个BeanFactory的自定义编辑器初始化给定的PropertyEditorRegistry。
* 用于创建和填充bean实例的beanwrapper,以及用于构造函数参数和工厂方法类型转换的SimpleTypeConverter。
*/
protected void registerCustomEditors(PropertyEditorRegistry registry) {
/** 1:尝试设置configValueEditorsActive为true */
if (registry instanceof PropertyEditorRegistrySupport) // eg1:true
((PropertyEditorRegistrySupport) registry).useConfigValueEditors();
/** 2:尝试调用所有PropertyEditorRegistrar的registerCustomEditors方法 */
if (!this.propertyEditorRegistrars.isEmpty()) { // eg1:propertyEditorRegistrars.size()=0
for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) {
try {
registrar.registerCustomEditors(registry);
}
catch (BeanCreationException ex) {
Throwable rootCause = ex.getMostSpecificCause();
if (rootCause instanceof BeanCurrentlyInCreationException) {
BeanCreationException bce = (BeanCreationException) rootCause;
String bceBeanName = bce.getBeanName();
if (bceBeanName != null && isCurrentlyInCreation(bceBeanName)) {
onSuppressedException(ex);
continue;
}
}
throw ex;
}
}
}
/** 3:尝试注册所有的customEditors */
if (!this.customEditors.isEmpty()) // eg1:customEditors.size()=0
this.customEditors.forEach((requiredType, editorClass) ->
registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass)));
}
2:调用所有配置了MergedBeanDefinitionPostProcessor实现类的postProcessMergedBeanDefinition方法
/** 2:调用所有配置了MergedBeanDefinitionPostProcessor实现类的postProcessMergedBeanDefinition方法 */
Object bean = instanceWrapper.getWrappedInstance(); // eg1:bean=Gun@2935
Class<?> beanType = instanceWrapper.getWrappedClass(); // eg1:beanType=Gun.class
if (beanType != NullBean.class) // eg1:true
mbd.resolvedTargetType = beanType;
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) { // eg1:true
try {
// eg1:MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); // 允许后处理器修改合并的bean定义
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
3:针对【单例】的【允许循环依赖】的【正在创建】的执行提前曝光 */
getEarlyBeanReference 记录创建bean的ObjectFactory
以AB循环依赖为例,类A中含有属性类B,而类B中又会含有属性类A,那么初始化 beanA的过程:当调用getBean(A)的时候,并不是直接去实例化A,而是先去检测缓存中 是否有已经创建好的bean,或者是否已经存在创建好的ObjectFactory,而此时对于A的 ObjectFactory我们早已经创建,所以便不会再去向后执行,而是直接调用 ObjectFactory#getObject()方法去创建A。
/** 3:针对【单例】的【允许循环依赖】的【正在创建】的执行提前曝光 */
boolean earlySingletonExposure = (mbd.isSingleton() && // eg1:true
this.allowCircularReferences && // eg1:true
isSingletonCurrentlyInCreation(beanName)); // eg1:true
if (earlySingletonExposure) // eg1:true
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
Object exposedObject = bean;
4:对bean进行填充操作,将各个属性值进行注入:populateBean(beanName, mbd, instanceWrapper);
调用该方法之前,已经获得了对应的对象,但对象是空属性或者默认属性的。一般会在配置里边对属性进行赋值操作,该方法就是对属性进行赋值操作。
populateBean方法,它是进行bean的属性数据填充注入的方法。其主要逻辑为:
① 如果bean的实例bw为null,但是却定义了bean的属性值,则抛异常;否则直接 return返回
② 针对配置了InstantiationAwareBeanPostProcessor实现类,那么会调用 postProcessAfterInstantiation方法
③ 获得配置的bean属性,然后根据注入类型(byName/byType)执行注入操作,即: autowireByName——通过set方法,根据name自动注入 和 autowireByType—— 通过set方法,根据type自动注入
④ 如果配置了后置处理器InstantiationAwareBeanPostProcesor,则会有机会调用其 postProcessProperties方法和postProcessPropertyValues方法
⑤ 执行依赖检查
⑥ 调用applyPropertyValues方法,将属性应用到bean中。
/**
* 用来自bean定义的属性值填充给定的BeanWrapper中的bean实例。
*/
// eg1:beanName="m416"
@SuppressWarnings("deprecation")
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
/** 1:如果bean的实例bw为null,却定义了bean的属性值,则抛异常;否则直接return返回 */
if (bw == null) { // eg1:false
if (mbd.hasPropertyValues())
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
else return;
}
/** 2:针对配置了InstantiationAwareBeanPostProcessor实现类,那么会调用postProcessAfterInstantiation方法 */
if (!mbd.isSynthetic() && // eg1:false
hasInstantiationAwareBeanPostProcessors()) // eg1:false
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware)
if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName))
return;
/** 3:获得配置的bean属性,然后根据注入类型(byName/byType)执行注入操作 */
// eg1:pvs = {ArrayList@2446} size = 3
// 0 = {PropertyValue@2448} "bean property 'name'"
// 1 = {PropertyValue@2449} "bean property 'bulletNums'"
// 2 = {PropertyValue@2450} "bean property 'desc'"
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
int resolvedAutowireMode = mbd.getResolvedAutowireMode(); // eg1:resolvedAutowireMode=AUTOWIRE_NO
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
/** 3.1:通过set方法,根据name自动注入 */
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) autowireByName(beanName, mbd, bw, newPvs);
/** 3.2:通过set方法,根据type自动注入 */
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) autowireByType(beanName, mbd, bw, newPvs);
pvs = newPvs;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); // eg1:false
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE); // eg1:false
PropertyDescriptor[] filteredPds = null;
/** 4:是否配置了后置处理器InstantiationAwareBeanPostProcesor */
if (hasInstAwareBpps) {
if (pvs == null) pvs = mbd.getPropertyValues();
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
/** 4-1:执行InstantiationAwareBeanPostProcessor#postProcessProperties(...)方法 */
PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null)
// 从给定的BeanWrapper中提取一组经过筛选的PropertyDescriptor,排除忽略的依赖关系类型或在忽略的依赖接口上定义的属性。
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
/** 4-2:执行InstantiationAwareBeanPostProcessor#postProcessPropertyValues(...)方法 */
pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) return;
}
pvs = pvsToUse;
}
}
/** 5:执行依赖检查 */
if (needsDepCheck) { // 是否需要执行依赖检测操作
if (filteredPds == null) filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
checkDependencies(beanName, mbd, filteredPds, pvs);
}
/** 6:将属性应用到bean中 */
if (pvs != null) // eg1:true
applyPropertyValues(beanName, mbd, bw, pvs);
}
步骤2中的判断条件:
/**
* 返回这个工厂是否持有一个InstantiationAwareBeanPostProcessor,它将在创建时应用于单例bean。
*/
protected boolean hasInstantiationAwareBeanPostProcessors() {
return !getBeanPostProcessorCache().instantiationAware.isEmpty(); // eg1:return false
}
/** 2:针对配置了InstantiationAwareBeanPostProcessor实现类,那么会调用postProcessAfterInstantiation方法 */
public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
@Nullable
default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
return null;
}
default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
return true;
}
@Nullable
default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
return null;
}
/** @deprecated */
@Deprecated
@Nullable
default PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
return pvs;
}
步骤3的执行注入操作:
autowireByName根据名称进行注入:
寻找bw中需要依赖注入的属性,通过递归属性名称,寻找相关bean实例对象,最后将其 加入到pvs中。源码如下所示:
/**
* 返回不满足条件的非简单bean属性的数组。这些可能是对工厂中其他bean的不满意的引用。不包含基本类型或字符串等简单属性。
*/
protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) {
Set<String> result = new TreeSet<>();
PropertyValues pvs = mbd.getPropertyValues();
PropertyDescriptor[] pds = bw.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) &&
!BeanUtils.isSimpleProperty(pd.getPropertyType())) {
result.add(pd.getName());
}
}
return StringUtils.toStringArray(result);
}
autowireByType根据类型进行注入:
/**
* 抽象方法定义了“按类型自动加载”(bean属性按类型)的行为。
* 其中,在bean工厂中必须只有一个属性类型的bean。这使得bean工厂对于小型命名空间的配置很简单,
* 但是对于大型应用程序,它的工作效果不如标准的Spring行为。
*/
protected void autowireByType(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
// 获得自定义TypeConverter
TypeConverter converter = getCustomTypeConverter();
if (converter == null) converter = bw;
Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
// 获得属性名列表,并对每一个属性进行遍历赋值操作
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
try {
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
if (Object.class != pd.getPropertyType()) {
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd); // 探测指定属性的setXxx方法
boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered);
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
/**
* 解析指定beanName的属性所匹配的值,并把解析到的属性名称存储在autowiredBeanNames中。
* 当属性存在多个封装bean时(@Autowired private List<A> aList)将会找到所有匹配A类型的bean并将其注入进去
*/
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);
}
}
}
④ - ③ - ① resolveDependency封装了依赖查找的各种情况
在doResolveDependency(...)方法中,封装了查找依赖的逻辑代码。
快速查找:@Autowired注解处理场景。AutowiredAnnotationBeanPostProcessor处理 @Autowired注解时,如果注入的对象只有一个,会将该bean对应的名称缓存起来,下次 直接通过名称查找会快很多。
注入指定值:@Value注解处理场景。QualifierAnnotationAutowireCandidateResolver 处理@Value注解时,会读取@Value对应的值进行注入。如果是String要经过三个过程: ①占位符处理 -> ②EL表达式解析 -> ③类型转换,这也是一般的处理过程, BeanDefinitionValueResolver处理String对象也是这个过程。
集合依赖查询:直接全部委托给resolveMultipleBeans方法。
单个依赖查询:先调用findAutowireCandidates查找所有可用的依赖,如果有多个依赖, 则根据规则匹配:@Primary -> @Priority -> ③ 方法名称或字段名称。
@Override
@Nullable
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
/** 1:Optional类型的特殊处理 */
if (Optional.class == descriptor.getDependencyType())
return createOptionalDependency(descriptor, requestingBeanName);
/** 2:ObjectFactory类型和ObjectProvider类型的特殊处理 */
else if (ObjectFactory.class == descriptor.getDependencyType() || ObjectProvider.class == descriptor.getDependencyType())
return new DependencyObjectProvider(descriptor, requestingBeanName);
/** 3:javaxInjectProviderClass类型的特殊处理 */
else if (javaxInjectProviderClass == descriptor.getDependencyType())
return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
/** 4:通用处理逻辑 */
else {
// SimpleAutowireCandidateResolver#getLazyResolutionProxyIfNecessary(...)
Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(descriptor, requestingBeanName);
if (result == null) // 默认的getLazyResolutionProxyIfNecessary(...)方法返回null
result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
return result;
}
}
/**
* 封装了依赖查找的各种情况
* 【快速查找】@Autowired注解处理场景。AutowiredAnnotationBeanPostProcessor处理@Autowired注解时,如果注入的对象只有一个,会将该bean对应的名称缓存起来,下次直接通过名称查找会快很多。
* 【注入指定值】@Value注解处理场景。QualifierAnnotationAutowireCandidateResolver处理@Value注解时,会读取@Value对应的值进行注入。
* 如果是String要经过三个过程:①占位符处理 -> ②EL表达式解析 -> ③类型转换,这也是一般的处理过程,BeanDefinitionValueResolver处理String对象也是这个过程。
* 【集合依赖查询】直接全部委托给resolveMultipleBeans方法。
* 【单个依赖查询】先调用findAutowireCandidates查找所有可用的依赖,如果有多个依赖,则根据规则匹配:@Primary -> @Priority -> ③方法名称或字段名称。
*/
@Nullable
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
try {
/** 1:快速查找,根据名称查找。AutowiredAnnotationBeanPostProcessor.ShortcutDependencyDescriptor会用到 */
Object shortcut = descriptor.resolveShortcut(this);
if (shortcut != null) return shortcut;
/** 2:注入指定值,QualifierAnnotationAutowireCandidateResolver解析@Value会用到 */
Class<?> type = descriptor.getDependencyType();
Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
if (value != null) {
/** 2-1:占位符解析 */
if (value instanceof String) {
String strVal = resolveEmbeddedValue((String) value);
BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null);
/** 2-2:Spring EL 表达式 */
value = evaluateBeanDefinitionString(strVal, bd);
}
/** 2-3:类型转换 */
TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
try {
return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
}
catch (UnsupportedOperationException ex) {
return (descriptor.getField() != null ?
converter.convertIfNecessary(value, type, descriptor.getField()) :
converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
}
}
/** 3:集合依赖,如:Array、List、Set、Map。内部查找依赖也是使用findAutowireCandidates */
Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
if (multipleBeans != null) return multipleBeans;
/** 4:单个依赖查询 */
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
/** 4-1:没有查找到依赖,判断descriptor.require */
if (matchingBeans.isEmpty()) {
if (isRequired(descriptor))
raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
return null;
}
/** 4-2:有多个,如何过滤 */
String autowiredBeanName;
Object instanceCandidate;
if (matchingBeans.size() > 1) {
/** 4-2-1:@Primary -> @Priority -> 方法名称或字段名称匹配 */
autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
/** 4-2-2:根据是否必须,抛出异常。注意这里如果是集合处理,则返回null */
if (autowiredBeanName == null) {
if (isRequired(descriptor) || !indicatesMultipleBeans(type))
return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
else
return null;
}
instanceCandidate = matchingBeans.get(autowiredBeanName);
}
else {
Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
autowiredBeanName = entry.getKey(); // 获得beanName
instanceCandidate = entry.getValue(); // 获得待选实例对象
}
if (autowiredBeanNames != null)
autowiredBeanNames.add(autowiredBeanName);
/** 4-3:实际上调用 getBean(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; // 返回待注入的bean
}
finally {
ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
}
}
步骤6的:将属性应用到bean中
程序运行到这里,已经完成了对所有注入属性的获取,但是获取的属性是以PropertyValues 形式存在的,并没有应用到已经实例化的bean中,这项工作就是在applyPropertyValues方法中实现的,其具体实现步骤如下所示:
① 如果pvs是MutablePropertyValues类型,那么调用getPropertyValueList方法获取属性 列表original
② 如果pvs不是MutablePropertyValues类型,那么调用getPropertyValues方法获取属性 列表original
③ 获取对应的解析器BeanDefinitionValueResolver
④ 遍历属性列表original,将其转换为对应类的对应属性类型,并保存到deepCopy列表中
⑤ 将解析后的deepCopy维护的BeanWrapper中
/**
* 应用给定的属性值,解析此bean工厂中对其他bean的任何运行时引用。必须使用深复制,所以我们不会永久修改这个属性。
*/
// eg1:beanName="m416",pvs=MutablePropertyValues@2441
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
if (pvs.isEmpty()) // eg1:false
return;
if (System.getSecurityManager() != null && // eg1:false
bw instanceof BeanWrapperImpl)
((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
MutablePropertyValues mpvs = null;
List<PropertyValue> original;
/** 1:如果pvs是MutablePropertyValues类型,那么调用getPropertyValueList方法获取属性列表original */
if (pvs instanceof MutablePropertyValues) { // eg1:true
mpvs = (MutablePropertyValues) pvs;
// 如果mpvs中的值已经被转换为对应的类型,那么可以直接设置到bw中
if (mpvs.isConverted()) { // eg1:false
try {
bw.setPropertyValues(mpvs);
return;
}
catch (BeansException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
// eg1:original = {ArrayList@2446} size = 3
// 0 = {PropertyValue@2448} "bean property 'name'"
// 1 = {PropertyValue@2449} "bean property 'bulletNums'"
// 2 = {PropertyValue@2450} "bean property 'desc'"
original = mpvs.getPropertyValueList();
}
/** 2:如果pvs不是MutablePropertyValues类型,那么调用getPropertyValues方法获取属性列表original */
else original = Arrays.asList(pvs.getPropertyValues());
/** 3:获取对应的解析器 */
TypeConverter converter = getCustomTypeConverter();
if (converter == null) // eg1:converter=null
converter = bw;
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
List<PropertyValue> deepCopy = new ArrayList<>(original.size());
boolean resolveNecessary = false;
/** 4:遍历属性列表original,将其转换为对应类的对应属性类型 */
// eg1: original.size()=3,下面仅仅以第1个元素"name"为例
for (PropertyValue pv : original) {
/** 4-1:如果属性值已经被转换 */
if (pv.isConverted()) // eg1: false
deepCopy.add(pv);
/** 4-2:如果属性值没有被转换,则执行转换操作 */
else {
String propertyName = pv.getName(); // eg1: propertyName="name"
Object originalValue = pv.getValue(); // eg1: originalValue=TypedStringValue@2901
if (originalValue == AutowiredPropertyMarker.INSTANCE) { // eg1: false
Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
if (writeMethod == null)
throw new IllegalArgumentException("Autowire marker for property without write method: " + pv);
originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true);
}
/** 4-3 执行类型转换 */
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
Object convertedValue = resolvedValue; // eg1:resolvedValue="M416"
boolean convertible = bw.isWritableProperty(propertyName) && !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
if (convertible) // eg1:true
convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter); // eg1:convertedValue="M416"
if (resolvedValue == originalValue) { // eg1: false
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); // eg1:convertedValue="M416"
deepCopy.add(pv);
}
else {
resolveNecessary = true;
deepCopy.add(new PropertyValue(pv, convertedValue));
}
}
}
if (mpvs != null && !resolveNecessary) // eg1:true
mpvs.setConverted();
/** 5:将解析后的deepCopy维护的BeanWrapper中 */
try {
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
}
catch (BeansException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
步骤4-3:执行类型转换:
/**
* 给定一个PropertyValue,返回一个值,必要时解析工厂中对其他bean的引用。其值可以是:
* ① 一个BeanDefinition,它导致创建相应的新bean实例。这种“内部bean”的单例标志和名称总是被忽略:内部bean是匿名原型。
* ② 一个RuntimeBeanReference,其必须是解析的。
* ③ 一个ManagedList,这是一个特殊的集合,其中可能包含需要解析的RuntimeBeanReferences或集合。
* ④ 一个ManagedSet,还可能包含需要解析的RuntimeBeanReferences或集合。
* ⑤ 一个ManagedMap,在这种情况下,值可能是需要解析的RuntimeBeanReference或集合。
* ⑥ 一个普通对象或null,在这种情况下,它是单独存在的。
*/
// eg1:argName=MutablePropertyValues@2441,value=TypedStringValue@2901
@Nullable
public Object resolveValueIfNecessary(Object argName, @Nullable Object value) {
if (value instanceof RuntimeBeanReference) { // eg1;false
RuntimeBeanReference ref = (RuntimeBeanReference) value;
return resolveReference(argName, ref);
}
else if (value instanceof RuntimeBeanNameReference) { // eg1;false
String refName = ((RuntimeBeanNameReference) value).getBeanName();
refName = String.valueOf(doEvaluate(refName));
if (!this.beanFactory.containsBean(refName)) {
throw new BeanDefinitionStoreException(
"Invalid bean name '" + refName + "' in bean reference for " + argName);
}
return refName;
}
else if (value instanceof BeanDefinitionHolder) { // eg1;false
BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
}
else if (value instanceof BeanDefinition) { // eg1;false
BeanDefinition bd = (BeanDefinition) value;
String innerBeanName = "(inner bean)" + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR +
ObjectUtils.getIdentityHexString(bd);
return resolveInnerBean(argName, innerBeanName, bd);
}
else if (value instanceof DependencyDescriptor) { // eg1;false
Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
Object result = this.beanFactory.resolveDependency(
(DependencyDescriptor) value, this.beanName, autowiredBeanNames, this.typeConverter);
for (String autowiredBeanName : autowiredBeanNames)
if (this.beanFactory.containsBean(autowiredBeanName))
this.beanFactory.registerDependentBean(autowiredBeanName, this.beanName);
return result;
}
else if (value instanceof ManagedArray) { // eg1;false
ManagedArray array = (ManagedArray) value;
Class<?> elementType = array.resolvedElementType;
if (elementType == null) {
String elementTypeName = array.getElementTypeName();
if (StringUtils.hasText(elementTypeName)) {
try {
elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader());
array.resolvedElementType = elementType;
}
catch (Throwable ex) {
throw new BeanCreationException(this.beanDefinition.getResourceDescription(), this.beanName,
"Error resolving array type for " + argName, ex);
}
}
else elementType = Object.class;
}
return resolveManagedArray(argName, (List<?>) value, elementType);
}
else if (value instanceof ManagedList) // eg1;false
return resolveManagedList(argName, (List<?>) value);
else if (value instanceof ManagedSet) // eg1;false
return resolveManagedSet(argName, (Set<?>) value);
else if (value instanceof ManagedMap) // eg1;false
return resolveManagedMap(argName, (Map<?, ?>) value);
else if (value instanceof ManagedProperties) { // eg1;false
Properties original = (Properties) value;
Properties copy = new Properties();
original.forEach((propKey, propValue) -> {
if (propKey instanceof TypedStringValue) propKey = evaluate((TypedStringValue) propKey);
if (propValue instanceof TypedStringValue) propValue = evaluate((TypedStringValue) propValue);
if (propKey == null || propValue == null)
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Error converting Properties key/value pair for " + argName + ": resolved to null");
copy.put(propKey, propValue);
});
return copy;
}
else if (value instanceof TypedStringValue) { // eg1;true
TypedStringValue typedStringValue = (TypedStringValue) value;
Object valueObject = evaluate(typedStringValue); // eg1:valueObject="M416"
try {
Class<?> resolvedTargetType = resolveTargetType(typedStringValue);
if (resolvedTargetType != null) // eg1:resolvedTargetType=null
return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
else
return valueObject; // eg1:return "M416"
}
catch (Throwable ex) {
throw new BeanCreationException(this.beanDefinition.getResourceDescription(), this.beanName,
"Error converting typed String value for " + argName, ex);
}
}
else if (value instanceof NullBean) return null;
else return evaluate(value);
}
步骤:value属于TypedStringValue类型 中的 evaluate方法:
/**
* 如有必要,将给定的值作为表达式求值。
*/
// eg1:value=TypedStringValue@2901
@Nullable
protected Object evaluate(TypedStringValue value) {
Object result = doEvaluate(value.getValue());
if (!ObjectUtils.nullSafeEquals(result, value.getValue())) // eg1:result="M416"
value.setDynamic();
return result; // eg1:return "M416"
}
/**
* 如果有必要,将给定的字符串作为表达式求值。
*/
// eg1:value="M416"
@Nullable
private Object doEvaluate(@Nullable String value) {
return this.beanFactory.evaluateBeanDefinitionString(value, this.beanDefinition);
}
/**
* 计算bean定义中包含的给定字符串,可能将其解析为表达式。
*/
// eg2:value="M416"
// eg1:value="com.muse.springdemo.entity.Gun"
@Nullable
protected Object evaluateBeanDefinitionString(@Nullable String value, @Nullable BeanDefinition beanDefinition) {
// 如果没有配置bean的表达式解析器,则直接返回
if (this.beanExpressionResolver == null) // eg1:beanExpressionResolver=null // eg2:beanExpressionResolver=null
return value; // eg1:return "com.muse.springdemo.entity.Gun" // eg2:return "M416"
Scope scope = null;
if (beanDefinition != null) {
String scopeName = beanDefinition.getScope();
if (scopeName != null) scope = getRegisteredScope(scopeName);
}
// 表达式解析操作
return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope));
}
evaluate中的if判断:
public static boolean nullSafeEquals(@Nullable Object o1, @Nullable Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
if (o1.equals(o2)) {
return true;
}
if (o1.getClass().isArray() && o2.getClass().isArray()) {
return arrayEquals(o1, o2);
}
return false;
}
步骤:value属于TypedStringValue类型 中的 resolveTargetType 方法:
/**
* 用给定的TypedStringValue解析目标类型。
*/
// eg1:value=TypedStringValue@2901
@Nullable
protected Class<?> resolveTargetType(TypedStringValue value) throws ClassNotFoundException {
if (value.hasTargetType()) // eg1:false
return value.getTargetType();
return value.resolveTargetType(this.beanFactory.getBeanClassLoader());
}
/**
* 确定要转换的类型,必要时使用指定的类名解析。当调用目标类型已经解析的指定类时,还将从其名称重新加载指定类。
*/
@Nullable
public Class<?> resolveTargetType(@Nullable ClassLoader classLoader) throws ClassNotFoundException {
String typeName = getTargetTypeName();
if (typeName == null) // eg1:typeName=null
return null;
Class<?> resolvedClass = ClassUtils.forName(typeName, classLoader);
this.targetType = resolvedClass;
return resolvedClass;
}
/**
* 返回要转换为的类型。
*/
@Nullable
public String getTargetTypeName() {
Object targetTypeValue = this.targetType; // eg1:targetType=null
if (targetTypeValue instanceof Class) // eg1:false
return ((Class<?>) targetTypeValue).getName();
else
return (String) targetTypeValue; // eg1:return null
}
所以 resloveBalueIfNecessory 方法返回“M416”, 即 resolvedValue为 “M416”
至此,populateBean(beanName, mbd, instanceWrapper) 方法执行完毕。
5. 调用初始化方法,例如:init-method
initializeBean 初始化bean
这个方法主要是针对我们配置的init-method属性,当Spring中程序已经执行过bean的实例化,并且进行了属性的填充,而就在这时将会调用用户设定的初始化方法。
/**
* 使用工厂回调函数、init方法和bean post处理器初始化给定的bean实例。
* 从{@link #createBean}调用传统定义的bean,从{@link #initializeBean}调用现有的bean实例。
*/
// eg1:beanName="m416",bean=Gun@2334,mbd=RootBeanDefinition@2332
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
/** 1:调用Aware类型的Bean的方法 */
if (System.getSecurityManager() != null) { // eg1:false
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else invokeAwareMethods(beanName, bean);
/** 2:调用配置的所有BeanPostProcessor#postProcessBeforeInitialization方法 */
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) // eg1:true
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
/** 3:激活用户自定义的init方法 */
try {
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException((mbd != null ? mbd.getResourceDescription() : null), beanName, "Invocation of init method failed", ex);
}
/** 4:调用配置的所有BeanPostProcessor#postProcessAfterInitialization方法 */
if (mbd == null || // eg1:false
!mbd.isSynthetic()) // eg1:true
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
return wrappedBean; // eg1:return Gun@2334
}
1、调用Aware类型的Bean方法
/** 调用Aware类型的Bean的方法 */
// eg1:beanName="m416",bean=Gun@2334
private void invokeAwareMethods(String beanName, Object bean) {
if (bean instanceof Aware) { // eg1:false
/** 1:处理BeanNameAware类型的bean */
if (bean instanceof BeanNameAware) ((BeanNameAware) bean).setBeanName(beanName);
/** 2:处理BeanClassLoaderAware类型的bean */
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
/** 3:处理BeanFactoryAware类型的bean */
if (bean instanceof BeanFactoryAware)
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
2、调用配置的所有BeanPostProcessor#postProcessBeforeInitialization方法 */
// eg1:existingBean=Gun@2334,beanName="m416"
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) { // eg1:getBeanPostProcessors().size()=0
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) return result;
result = current;
}
return result; // eg1:return Gun@2334
}
3、激活用户自定义的init方法
/**
* 现在让bean有机会做出响应,它的所有属性都设置好了,也有机会知道它拥有的bean工厂(这个对象)。这意味着检查bean是否实现了InitializingBean
* 或定义了自定义的init方法,如果实现了,就调用必要的回调函数。
*/
// eg1:beanName="m416",bean=Gun@2334
protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd) throws Throwable {
/** 1:调用InitializingBean#afterPropertiesSet()方法 */
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && // eg1:isInitializingBean=false
(mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {throw pae.getException();}
}
else
((InitializingBean) bean).afterPropertiesSet();
}
/** 2:调用自定义的init-method方法 */
if (mbd != null && bean.getClass() != NullBean.class) { // eg1:true
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) && // eg1:initMethodName=null
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
/**
* 在给定bean上调用指定的自定义init方法。由invokeInitMethods调用。可以在子类中重写,用于自定义带有参数的init方法的解析。
*/
protected void invokeCustomInitMethod(String beanName, Object bean, RootBeanDefinition mbd) throws Throwable {
/** 1:获得init-method方法的字符串名称 */
String initMethodName = mbd.getInitMethodName();
Assert.state(initMethodName != null, "No init method set");
/** 2:获得init-method对应的Method实例对象 */
Method initMethod = (mbd.isNonPublicAccessAllowed() ?
BeanUtils.findMethod(bean.getClass(), initMethodName) :
ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));
if (initMethod == null) {
if (mbd.isEnforceInitMethod()) throw new BeanDefinitionValidationException("Could not find an init method named '" +
initMethodName + "' on bean with name '" + beanName + "'");
else return;
}
/** 3:通过反射,执行init-method的方法调用 */
Method methodToInvoke = ClassUtils.getInterfaceMethodIfPossible(initMethod);
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
ReflectionUtils.makeAccessible(methodToInvoke);
return null;
});
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>)
() -> methodToInvoke.invoke(bean), getAccessControlContext()); // 通过反射,执行init-method的方法调用
}
catch (PrivilegedActionException pae) {
InvocationTargetException ex = (InvocationTargetException) pae.getException();
throw ex.getTargetException();
}
}
else {
try {
ReflectionUtils.makeAccessible(methodToInvoke);
// 通过反射,执行init-method的方法调用
methodToInvoke.invoke(bean);
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
6:针对需要执行【提前曝光】的单例
getSingleton:
/**
* 返回以给定名称注册的(原始)单例对象。检查已经实例化的单例,也允许对当前创建的单例进行早期引用(解析循环引用)。
* ① 尝试从singletonObjects中获取
* ② 尝试从earlySingletonObjects中获取
* ③ 尝试从singletonFactories中获取
*/
// eg2:beanName="m416",allowEarlyReference=false
// eg1:beanName="m416",allowEarlyReference=true
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
/** 1:尝试先从缓存【singletonObjects】中获取 */
// eg2:singletonObjects.size()=0
// eg1:singletonObjects.size()=0
Object singletonObject = this.singletonObjects.get(beanName);
/** 2:如果缓存中没有,并且当前的bean正在被创建 */
if (singletonObject == null && // eg1:singletonObject=null
isSingletonCurrentlyInCreation(beanName)) { // eg1:false // eg2:true
/** 2-1:再次尝试从缓存【earlySingletonObjects】中获取 */
singletonObject = this.earlySingletonObjects.get(beanName); // eg2:earlySingletonObjects.size()=0
/** 2-2:如果缓存中没有,并且允许早期依赖(allowEarlyReference=true)*/
if (singletonObject == null // eg2:true
&& allowEarlyReference) { // eg2:false
synchronized (this.singletonObjects) {
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null) {
/** 2-3:最后:尝试从缓存【singletonFactories】中获取对象工厂 */
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject(); // 通过对象工厂获得实例对象
this.earlySingletonObjects.put(beanName, singletonObject); // 维护到缓存中
this.singletonFactories.remove(beanName);
}
}
}
}
}
}
return singletonObject; // eg1:return null // eg2:return null
}
7:如果配置了destroy-method,这里需要注册以便于在销毁时候进行调用
Spring同时也提供了销毁方法的扩展入口,对于销毁方法的扩展,除了我们熟知的配置属 性destroy-method方法外,用户还可以注册后处理器 DestructionAwareBeanPostProcessor来统一处理bean的销毁方法。
/**
* 将给定bean添加到该工厂的一次性bean列表中,注册它的disposable bean接口和/或给定的destroy方法,在工厂关闭时调用(如果适用)。只适用于单例。
*/
// eg1:beanName="m416"
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null); // eg1:acc=null
/** 1:单例 并且 确定给定的bean需要在关闭时销毁 */
if (!mbd.isPrototype() && // eg1:true
requiresDestruction(bean, mbd)) { // eg1:false
/** 1-1:单例模式下注册需要销毁的bean,此方法中会处理实现DisposableBean的bean,并且对所有的bean使用DestructionAwareBeanPostProcessor处理 */
if (mbd.isSingleton())
registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, mbd,
getBeanPostProcessorCache().destructionAware, acc));
/** 1-2:自定义scope的处理 */
else {
Scope scope = this.scopes.get(mbd.getScope());
if (scope == null)
throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(
bean, beanName, mbd, getBeanPostProcessorCache().destructionAware, acc));
}
}
}
/**
* 确定给定bean是否需要在关闭时销毁。
* 默认实现会检查disablebean接口以及指定的destroy方法和注册的DestructionAwareBeanPostProcessors。
*/
protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) {
return (bean.getClass() != NullBean.class &&
(DisposableBeanAdapter.hasDestroyMethod(bean, mbd) ||
(hasDestructionAwareBeanPostProcessors() &&
DisposableBeanAdapter.hasApplicableProcessors(bean, getBeanPostProcessorCache().destructionAware))));
}
/**
* 将给定的bean添加到这个注册表中的一次性bean列表中。
* 一次性bean通常对应于已注册的单例,与bean名称匹配,但可能是不同的实例(例如,单例的Disposable bean适配器没有自然地实现Spring的Disposable bean接口)。
*/
public void registerDisposableBean(String beanName, DisposableBean bean) {
synchronized (this.disposableBeans) {
this.disposableBeans.put(beanName, bean);
}
}
DisposableBean放到缓存中,其中包含destroy方法。需要销毁某个bean的时候,会去缓存中找有没有对应的disposableBean。
第4步中:将beanName从singletonsCurrentlyInCreation中移除掉
/**
* 创建单例后的回调。默认实现将单例标记为不再创建中。
*/
// eg1:beanName="m416"
protected void afterSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && // eg1:inCreationCheckExclusions.size()=0
!this.singletonsCurrentlyInCreation.remove(beanName)) { // eg1:singletonsCurrentlyInCreation=["m416"]
throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
}
}
还是/** 6:创建bean的单例实例对象 */
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
/**
* 覆盖,以便隐式地将当前创建的bean注册为依赖于在Supplier回调期间以编程方式检索的其他bean。
*/
@Override
protected Object getObjectForBeanInstance(Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
String currentlyCreatedBean = this.currentlyCreatedBean.get();
if (currentlyCreatedBean != null) // eg1:currentlyCreatedBean=null
registerDependentBean(beanName, currentlyCreatedBean);
// eg1:AbstractBeanFactory#getObjectForBeanInstance
return super.getObjectForBeanInstance(beanInstance, name, beanName, mbd); // eg1:return Gun@2334
}
/**
* 获取给定bean实例的对象,对于FactoryBean,要么是bean实例本身,要么是它创建的对象。
*/
// eg1:beanInstance=Gun@2334,name="m416",beanName="m416",mbd=null
protected Object getObjectForBeanInstance(Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
/** 1:如果name是以"&"为前缀,并且beanInstance是FactoryBean实例对象,则返回beanInstance */
if (BeanFactoryUtils.isFactoryDereference(name)) { // eg1:false
if (beanInstance instanceof NullBean) return beanInstance;
if (!(beanInstance instanceof FactoryBean)) throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
if (mbd != null) mbd.isFactoryBean = true;
return beanInstance;
}
/** 2:如果不是FactoryBean实例对象,则直接返回 */
if (!(beanInstance instanceof FactoryBean)) // eg1:true
return beanInstance; // eg1:return Gun@2334
/** 3:如果name不是以"&"为前缀,并且beanInstance是FactoryBean实例对象,则通过getObject()方法获得bean实例对象 */
Object object = null;
if (mbd != null)
mbd.isFactoryBean = true;
else
/** 3-1:尝试从缓存factoryBeanObjectCache中获得bean */
object = getCachedObjectForFactoryBean(beanName);
/** 4:如果缓存中没有,就创建一个bean实例对象 */
if (object == null) {
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
/** 4-1:将存储XML配置信息的GenericBeanDefinition转换为RootBeanDefinition,如果指定beanName是子bean,则合并父类属性 */
if (mbd == null && containsBeanDefinition(beanName))
mbd = getMergedLocalBeanDefinition(beanName);
/** 4-2:调用getObject()方法获的真实的bean对象 */
boolean synthetic = (mbd != null && mbd.isSynthetic()); // true:用户自定义的 false:应用程序定义的
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
/**
* 从给定的FactoryBean获取要公开的对象
*/
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
/** 1:如果factory是单例的 并且 beanName对应的bean已经被创建了 */
if (factory.isSingleton() && containsSingleton(beanName)) {
synchronized (getSingletonMutex()) {
Object object = this.factoryBeanObjectCache.get(beanName);
/** 1-1:如果没有创建缓存,则向缓存factoryBeanObjectCache中添加beanName与Bean实例对象的对应关系 */
if (object == null) {
/** 1-2:创建bean的实例对象。即:调用FactoryBean#getObject()获得 */
object = doGetObjectFromFactoryBean(factory, beanName);
Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
if (alreadyThere != null)
object = alreadyThere;
else {
/** 1-3:是否执行后置处理(xxxPostProcess)*/
if (shouldPostProcess) {
// 如果bean正在创建,则直接返回
if (isSingletonCurrentlyInCreation(beanName)) return object;
// 将beanName加入到缓存singletonsCurrentlyInCreation中
beforeSingletonCreation(beanName);
try {
/** 1-4:bean在初始化后会调用所有注册的BeanPostProcessor类的postProcessAfterInitialization方法 */
object = postProcessObjectFromFactoryBean(object, beanName); // AbstractAutowireCapableBeanFactory
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Post-processing of FactoryBean's singleton object failed", ex);
}
finally {
//将beanName从缓存singletonsCurrentlyInCreation中移除
afterSingletonCreation(beanName);
}
}
// 如果bean已经被创建,则向缓存中维护beanName与FactoryBean实例对象的对应关系
if (containsSingleton(beanName))
this.factoryBeanObjectCache.put(beanName, object);
}
}
return object;
}
}
/** 2:如果factory不是单例的,或者bean没有被创建,则只获得bean实例,不需要维护到factoryBeanObjectCache中 */
else {
/** 2-1:创建bean的实例对象。即:调用FactoryBean#getObject()获得 */
Object object = doGetObjectFromFactoryBean(factory, beanName);
if (shouldPostProcess) {
try {
/** 2-2:bean在初始化后会调用所有注册的BeanPostProcessor类的postProcessAfterInitialization方法 */
object = postProcessObjectFromFactoryBean(object, beanName); // AbstractAutowireCapableBeanFactory
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
}
}
return object;
}
}
getObjectForBeanInstance 从bean中获得真正的实例对象:
得到bean的实例之后,要做的第一步就是调用getObjectForBeanInstance(...)方法 来检测正确性,即:检测当前bean是否是FactoryBean类型,如果是,那么需要调用它的 getObject()方法作为返回值
/**
* 从给定的FactoryBean获取要公开的对象。
*/
private Object doGetObjectFromFactoryBean(FactoryBean<?> factory, String beanName) throws BeanCreationException {
Object object;
try {
if (System.getSecurityManager() != null) {
AccessControlContext acc = getAccessControlContext();
try {
object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else
/** 调用FactoryBean#getObject()方法获得实例对象 */
object = factory.getObject();
}
catch (FactoryBeanNotInitializedException ex) {
throw new BeanCurrentlyInCreationException(beanName, ex.toString());
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
}
if (object == null) {
if (isSingletonCurrentlyInCreation(beanName))
throw new BeanCurrentlyInCreationException(beanName, "FactoryBean which is currently in creation returned null from getObject");
object = new NullBean();
}
return object;
}
/** 7:创建原型对象 */
/** 8:创建指定scope类型的对象 */
/** 9:检查需要的类型是否符合bean的实际类型,如果不同,则对其进行类型转换 */
// eg1:name="m416",bean=Gun@2334,requiredType=Gun.class
@SuppressWarnings("unchecked")
<T> T adaptBeanInstance(String name, Object bean, @Nullable Class<?> requiredType) {
if (requiredType != null && !requiredType.isInstance(bean)) { // eg1:false
try {
Object convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null)
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
return (T) convertedBean;
}
catch (TypeMismatchException ex) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean; // eg1:return Gun@2334
}