在上一篇,我们看到这样的代码:
DefaultListableBeanFactory beanFactory = createBeanFactory();
.... synchronized (this.beanFactoryMonitor) { this.beanFactory = beanFactory; }
知道Application将getBean方法的实现委托给了DefaultListableBeanFactory,在DefaultListableBeanFactory按F4键我们可以看到这样的继承结构:
其中XmlBeanFactory我们经常用到,从上图看知道咋回事了吧?我们来看看DefaultListableBeanFactory的getBean方法吧:
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
doGetBean方法位于AbstractBeanFactory之中,它调用了createBean子方法:
protected abstract Object createBean(String beanName, RootBeanDefinition mbd, Object[] args)
throws BeanCreationException;
又是一个抽象方法,看来doGetBean又是一个模板设计模式的具体体现,Spring里面很多很多这样的用法,有时候会转晕,但是没有办法,他们就是这样设计的,至于为什么这么设计,以后再说明!createBean方法被实现在了AbstractAutowireCapableBeanFactory类中:
public <T> T createBean(Class<T> beanClass) throws BeansException {
// Use prototype bean definition, to avoid registering bean as dependent bean.
RootBeanDefinition bd = new RootBeanDefinition(beanClass);
bd.setScope(SCOPE_PROTOTYPE);
return (T) createBean(beanClass.getName(), bd, null);
}
看到了吧,这里把当前要求的Bean对应的BeanDefinition初始化出来了,作为创建Bean的基础。
protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
// Make sure bean class is actually resolved at this point.
//也就是看看能不能实例化!
resolveBeanClass(mbd, beanName);
// Prepare method overrides.
try {
mbd.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbd.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
//如果配置了psotprocessor就返回proxy,动态代理会在取得bean之后的操作后
//去处理psotprocessor
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
Object bean = resolveBeforeInstantiation(beanName, mbd);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
Object beanInstance = doCreateBean(beanName, mbd, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
那么doCreateBean应该就是了,请快些看下篇