一般调用方式是
MyJavaBean bean = (MyJavaBean) bf.getBean("myJavaBean");
首先获取BeanFactory(DefaultListableBeanFactory类),然后调用AbstractBeanFactory类中的getBean方法
@Override
public Object getBean(String name) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(name);
}
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
真正的调用在doGetBean中
protected <T> T doGetBean(
final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {
//获取beanName 主要为处理别名和&beanName这两种形式
final String beanName = transformedBeanName(name);
Object bean;
/**
分别从singletonObjects(beanName->beanName instance),earlySingletonObjects(beanName->beanName instance)主要用于检测循环引用,可以在bean还在创建的过程中提前获取bean,singletonFactories(beanName->objectFactory)三个缓存中获取bean
*/
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
/**
如果通过缓存获取到了bean的实例,还需要对该实例进行验证
因为不管是从缓存中获取到的bean还是我们通过不同的scope策略加载的bean,都是bean的原始形式,不一定是我们最终需要的bean
例如我们定义一个工厂bean,那么此时获取的是工厂bean本身,但实际上我们需要的是bean中定义的factory-bean方法返回的bean
*/
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
//如果没有从缓存中获取bean实例,首先检查是否存在循环引用,只有在单例情况下才尝试解决循环引用
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
//若已经加载的BeanDefinition中不包含该beanName,则从(父容器)parentBeanFactory中检测,若存在,则调用parentBeanFactory加载该bean
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
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);
}
}
//如果不仅仅做类型检测则是要创建bean,在这里做记录,并清除mergedBeanDefinitions中的缓存
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
/**
(1)验证beanName对应的BeanDefinition是否存在 若不存在直接抛异常
(2)若该bean是子bean则要合并父类的相关属性
(3)合并后要验证mergedBeanDefinition,该bean不能为抽象bean
*/
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
//若存在依赖则递归实例化依赖的bean,该依赖由depends-on属性引入
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dependsOnBean : dependsOn) {
if (isDependent(beanName, dependsOnBean)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
}
registerDependentBean(dependsOnBean, beanName);
getBean(dependsOnBean);
}
}
//根据不同的scope创建bean的实例
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
final 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, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
//检查获取的bean实例是否符合bean的实际类型
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
try {
return getTypeConverter().convertIfNecessary(bean, requiredType);
}
catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type [" +
ClassUtils.getQualifiedName(requiredType) + "]", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}