在这5个类中AbstractBeanFactory完成了getBean()方法的具体实现
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
public T getBean(String name, Class requiredType) throws BeansException {
return doGetBean(name, requiredType, null, false);
}
public Object getBean(String name, Object... args) throws BeansException {
return doGetBean(name, null, args, false);
}
public T getBean(String name, Class requiredType, Object... args) throws BeansException {
return doGetBean(name, requiredType, args, false);
}
这几个方法最终调用的是doGetBean方法
protected T doGetBean(
final String name, final Class requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {
//去除&符号,因为当配置文件中的class属性配置的实现类是FactoryBean时,通过getBean()方法返回的不是FactoryBean本身,
//而是FactoryBean#getObject()方法所返回的对象,相当于FactoryBean#getObject()代理了getBean()方法,如果希望获取FactoryBean的实例,需要在beanName前加上“&”符号,即getBean("&beanName")
//在这里要获取的是bean的实例,所以要去掉&符号
final String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
//-------------------------------------方法1------------------------------------------//
//从缓存中获取单利的bean
Object sharedInstance = getSingleton(beanName);
//-------------------------------------方法1------------------------------------------//
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
//从已经加载的object中获取bean
//-------------------------------------方法2------------------------------------------//
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
//-------------------------------------方法2------------------------------------------//
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
//检查要获取的bean是不是当前线程正在创建中的bean
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
//检查当前BeanFactory的父类BeanFactory是不是不为空,并且要获取的bean不包含在当前BeanFactory中
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
//还原要获取的bean的beanName
String nameToLookup = originalBeanName(name);
//调用parentBeanFactory获取bean
if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
//typeCheckOnly默认为false
if (!typeCheckOnly) {
//如果当前bean不在正在创建中的bean的缓存集合(alreadyCreated)中,就加进去
markBeanAsCreated(beanName);
}
try {
//合并要获取的bean的属性并把属性赋值给一个RootBeanDefinition
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
//检查合并之后的RootBeanDefinition的是不是抽象的,还会检查如果获取bean的参数不空的情况下,bean的类型是singleton的就会报错,因为单利情况下bean都是一样的,只有prototype情况下才能不一致
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
//获取当前bean依赖的bean的名称的数组
String[] dependsOn = mbd.getDependsOn();
//如果依赖不为空就先加载依赖到的bean
if (dependsOn != null) {
for (String dependsOnBean : dependsOn) {
getBean(dependsOnBean);
//将要获取的bean的beanName和所依赖到的bean的beanName之间的关系缓存起来
registerDependentBean(dependsOnBean, beanName);
}
}
// Create bean instance.
//开始创建单利bean实例
if (mbd.isSingleton()) {
//--------------------------------------方法4------------------------------//
sharedInstance = getSingleton(beanName, new ObjectFactory
对上面的标注的方法分别进行解析:
-
- getSingleton方法 DefaultSingletonBeanRegistry类中
getSingleton方法的详解
单例在Spring的同一个容器内只会被创建一次,后续在获取bean,就直接从单例缓存中获取了。这里也只是尝试获取,首先尝试从缓存中加载,如果加载不成功则再次尝试从singletonFactories中加载。因为在创建单例bean 的时候会存在依赖注入的情况,而在创建依赖的时候为了避免循环依赖,在Spring中创建bean 的原则是不等bean创建完就会将创建bean 的ObjectFactory提早曝光加入到缓存中,一旦下一个bean创建时候需要依赖上一个bean则直接使用ObjectFactory。
- getSingleton方法 DefaultSingletonBeanRegistry类中
-
- getObjectForBeanInstance方法 AbstractBeanFactory类中
getObjectForBeanInstance方法的详解
如果从缓存中得到了bean的原始状态,则需要对bean进行实例化。缓存中记录的只是最原始的bean状态,并不一定是我们最终想要的bean。
假如我们需要对工厂bean进行处理,那么这里得到的其实是工厂bean的初始状态,但是我们正真需要的是工程bean中定义的factory-method方法中返回的bean,而getObjectForBeanInstance就是完成这个工作的
- getObjectForBeanInstance方法 AbstractBeanFactory类中
- 3.获取单例对象时候调用DefaultSingletonBeanRegistry类getSingleton方法的第二个参数ObjectFactory实现了ObjectFactory接口的getObject方法,调用的createBean方法
createBean方法的详解 -
- public Object getSingleton(String beanName, ObjectFactory> singletonFactory) 方法
这个方法与上面的getSingleton不同之处在于这个方法是在创建了bean对象,并初始化之后调用的,作用是从bean对象中获取单例的bean同时放到单例缓存中
- public Object getSingleton(String beanName, ObjectFactory> singletonFactory) 方法
public Object getSingleton(String beanName, ObjectFactory> singletonFactory) {
Assert.notNull(beanName, "'beanName' must not be null");
synchronized (this.singletonObjects) {
//在已经注册了的单例map集合(singletonObjects)中获取特定beanName的bean
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while the singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
//singletonObjects中获取不到bean的时候,说明是新创建的bean,这个时候需要先检查满足其中一个
//1.当前创建检查中排除的beanName集合中包含这个创建中的单例beanName
//2.当前正在创建的单例beanName集合中不包含这个单例bean的beanName
beforeSingletonCreation(beanName);
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet();
}
try {
//从创建的bean中获取bean对象
singletonObject = singletonFactory.getObject();
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
//从当前正在创建的单例beanName集合中删除当前的beanName
afterSingletonCreation(beanName);
}
//加入到单例缓存中
addSingleton(beanName, singletonObject);
}
//返回单例对象
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
}