我们首先来看下BeanFacroty接口
- package org.springframework.beans.factory;
- import org.springframework.beans.BeansException;
- public interface BeanFactory {
- String FACTORY_BEAN_PREFIX = "&";
- Object getBean(String name) throws BeansException;
- Object getBean(String name, Class requiredType) throws BeansException;
- boolean containsBean(String name);
- String[] getAliases(String name) throws NoSuchBeanDefinitionException;
- }
可以看出,BeanFactory定义了Factory的基本方法,他能够生成Bean以及辨别Bean是否包含在factory中,以及从一个Bean的名字的到其别名;
- package org.springframework.beans.factory;
- public interface HierarchicalBeanFactory extends BeanFactory {
- BeanFactory getParentBeanFactory();
- boolean containsLocalBean(String name);
- }
HierarchicalBeanFactory在beanFactory的基础上,提供了BeanFactory能够集成父容器的功能,从而形成了工厂链;
- public interface ConfigurableBeanFactory extends HierarchicalBeanFactory {
- void setParentBeanFactory(BeanFactory parentBeanFactory);
- void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor);
- void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);
- int getBeanPostProcessorCount();
- void registerAlias(String beanName, String alias) throws BeansException;
- void registerSingleton(String beanName, Object singletonObject) throws BeansException;
- boolean containsSingleton(String beanName);
- void destroySingletons();
- }
ConfigurableBeanFactory有继承了HierarchicalBeanFactory 接口,在HierarchicalBeanFactory 接口的基础上,有实现了BeanFactory的一些可配置功能,比如说增加VBeanPostProcessor,注册别名,注册单列等等;
- public interface ListableBeanFactory extends BeanFactory {
- boolean containsBeanDefinition(String beanName);
- int getBeanDefinitionCount();
- String[] getBeanDefinitionNames();
- Map getBeansOfType(Class type, boolean includePrototypes, boolean includeFactoryBeans)
- throws BeansException;
- }
而ListableBeanFactory能够列出此工厂中的BeanDifinition的信息;一个BeanDifinition就是一个Bean,他不仅包含了Bean对象,并且他里面每一个配置文件就是其的一个属性,比如lazy-init,dependcy-check等等;
在这里,我们可以先来看看BeanDifinition;
可见,在接口设计的时候,先抽象出来接口,由于子类之间有共同的功能实现,那么,再次抽象出抽象类,尽量把相同的代码往上推,其次,最终实现;
ChildBeanDefinition和RootBeanDefinition分别表示两种BeanDefition类型,ChildBeanDefinition表示继承了别的Bean的配置信息的Bean元素,所以,他有一个直接的
private final String parentName;
public String getParentName() {
return parentName;
}
所以,在得到这个bean的时候,我们必须一层一层的往上组合merge才能得到完整的Bean的配置信息;
而大多数时候,我们使用RootBeanFactory,表示,这个Bean所具有的配置信息完全由他自己所定义;
弄清楚这个以后,我们从XmlBeanFactory来反推查看类结构;
在这里,我们可以看出类图结构错综复杂,很是繁琐,有些类在借口的实现过程中间出现了重复,我们来从上而下的分析这类图:
(1)AutowireCapableBeanFactory:实现了自动装配的功能,在此接口中,定义了几种自动装配的类型,比如:
- int AUTOWIRE_BY_NAME = 1;
- int AUTOWIRE_BY_TYPE = 2;
- int AUTOWIRE_CONSTRUCTOR = 3;
- int AUTOWIRE_AUTODETECT = 4;
并且能够检查Bean自动装配的BeanPostProcessors的postProcessAfter/BeforeInitialization并且应用;
- Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
- throws BeansException;
- Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
- throws BeansException;
AbstractBeanFactory则是上述接口的 一个抽象实现,很多方法都在此方法中得到了实现;
首先是BeanFactory功能的实现;如:
- public Object getBean(String name, Class requiredType, Object[] args) throws BeansException {
- String beanName = transformedBeanName(name);
- //对名字进行了预处理,去掉了“&”
- Object bean = null;
- // Eagerly check singleton cache for manually registered singletons.
- Object sharedInstance = null;
- synchronized (this.singletonCache) {
- //是否是共享的实例;若是,则从缓存中取出;
- sharedInstance = this.singletonCache.get(beanName);
- }
- if (sharedInstance != null) {
- //此例是否正在生成?
- if (isSingletonCurrentlyInCreation(beanName)) {
- if (logger.isDebugEnabled()) {
- logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
- "' that is not fully initialized yet - a consequence of a circular reference");
- }
- }
- else {
- if (logger.isDebugEnabled()) {
- logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
- }
- }
- bean = getObjectForSharedInstance(name, sharedInstance);
- }
- else {
- // Fail if we're already creating this singleton instance:
- // We're assumably within a circular reference.
- if (isSingletonCurrentlyInCreation(beanName)) {
- throw new BeanCurrentlyInCreationException(beanName);
- }
- // Check if bean definition exists in this factory.
- if (getParentBeanFactory() != null && !containsBeanDefinition(beanName)) {
- // Not found -> check parent.
- if (getParentBeanFactory() instanceof AbstractBeanFactory) {
- // Delegation to parent with args only possible for AbstractBeanFactory.
- return ((AbstractBeanFactory) getParentBeanFactory()).getBean(name, requiredType, args);
- }
- else if (args == null) {
- // No args -> delegate to standard getBean method.
- //通过父容器来取得Bean
- return getParentBeanFactory().getBean(name, requiredType);
- }
- else {
- throw new NoSuchBeanDefinitionException(beanName,
- "Cannot delegate to parent BeanFactory because it does not supported passed-in arguments");
- }
- }
- //得到一个完整的BeanDefinition;
- RootBeanDefinition mergedBeanDefinition = getMergedBeanDefinition(beanName, false);
- checkMergedBeanDefinition(mergedBeanDefinition, beanName, requiredType, args);
- // Create bean instance.
- //如果是单例,那么就添加在单例map中去;
- //在这里,你可以看成享元模式的一种灵活应用,
- if (mergedBeanDefinition.isSingleton()) {
- synchronized (this.singletonCache) {
- // Re-check singleton cache within synchronized block.
- sharedInstance = this.singletonCache.get(beanName);
- if (sharedInstance == null) {
- if (logger.isDebugEnabled()) {
- logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
- }
- //标示一下,此实例Bean正在生成,以免Sington重复创建,变相达到线程安全;
- this.currentlyInCreation.add(beanName);
- try {
- sharedInstance = createBean(beanName, mergedBeanDefinition, args);
- addSingleton(beanName, sharedInstance);
- }
- 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.
- destroyDisposableBean(beanName);
- throw ex;
- }
- finally {
- //beanDefinition生成完毕,从正在创建数组中移除
- this.currentlyInCreation.remove(beanName);
- }
- }
- }
- bean = getObjectForSharedInstance(name, sharedInstance);
- }
- else {
- //如果是原型Bean,,那么我们直接应用这个类型来生成一个实例
- bean = createBean(beanName, mergedBeanDefinition, args);
- }
- }
- // Check if required type matches the type of the actual bean instance.
- if (requiredType != null && !requiredType.isAssignableFrom(bean.getClass())) {
- throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
- }
- return bean;
- }
(2)HierarchicalBeanFactory的实现:
- public BeanFactory getParentBeanFactory() {
- return parentBeanFactory;
- }
- public boolean containsLocalBean(String name) {
- String beanName = transformedBeanName(name);
- return (containsSingleton(beanName) || containsBeanDefinition(beanName));
- }
判断一个Bean是否在本地配置;而不是在父工厂中生成;
我们可以抽取出mergeBeanDefinition来看看:
- protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
- throws BeanDefinitionStoreException {
- //如果是根Bean.则返回,退出嵌套;
- if (bd instanceof RootBeanDefinition) {
- // Return root bean definition as-is.
- return (RootBeanDefinition) bd;
- }
- else if (bd instanceof ChildBeanDefinition) {
- // Child bean definition: needs to be merged with parent.
- ChildBeanDefinition cbd = (ChildBeanDefinition) bd;
- RootBeanDefinition pbd = null;
- try {
- if (!beanName.equals(cbd.getParentName())) {
- //在这里进行了嵌套;
- pbd = getMergedBeanDefinition(cbd.getParentName(), true);
- }
- else {
- if (getParentBeanFactory() instanceof AbstractBeanFactory) {
- AbstractBeanFactory parentFactory = (AbstractBeanFactory) getParentBeanFactory();
- pbd = parentFactory.getMergedBeanDefinition(cbd.getParentName(), true);
- }
- else {
- throw new NoSuchBeanDefinitionException(cbd.getParentName(),
- "Parent name '" + cbd.getParentName() + "' is equal to bean name '" + beanName +
- "': cannot be resolved without an AbstractBeanFactory parent");
- }
- }
- }
- catch (NoSuchBeanDefinitionException ex) {
- throw new BeanDefinitionStoreException(cbd.getResourceDescription(), beanName,
- "Could not resolve parent bean definition '" + cbd.getParentName() + "'", ex);
- }
- // Deep copy with overridden values.
- RootBeanDefinition rbd = new RootBeanDefinition(pbd);
- rbd.overrideFrom(cbd);
- // Validate merged definition: mainly to prepare method overrides.
- try {
- rbd.validate();
- }
- catch (BeanDefinitionValidationException ex) {
- throw new BeanDefinitionStoreException(rbd.getResourceDescription(), beanName,
- "Validation of bean definition failed", ex);
- }
- return rbd;
- }
- else {
- throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
- "Definition is neither a RootBeanDefinition nor a ChildBeanDefinition");
- }
- }
- sharedInstance = createBean(beanName, mergedBeanDefinition, args);
- addSingleton(beanName, sharedInstance);
这段代码大量的应用了模板模式:createBean是在AbstractAutowireCapableBeanFactory类中实现的:
protected Object createBean(String beanName, RootBeanDefinition mergedBeanDefinition, Object[] args)
throws BeanCreationException {
// Guarantee initialization of beans that the current one depends on.
if (mergedBeanDefinition.getDependsOn() != null) {
for (int i = 0; i < mergedBeanDefinition.getDependsOn().length; i++) {
//将依赖的类加载进来;
getBean(mergedBeanDefinition.getDependsOn()[i]);
}
}
bean = applyBeanPostProcessorsBeforeInstantiation(mergedBeanDefinition.getBeanClass(), beanName);
会为这个Bean生成一个代理,每次都会调用拦截的方法;
AbstractAutoProxyCreator:
public Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException {
if (isInfrastructureClass(beanClass, beanName)) {
return null;
}
// Create proxy here if we have a custom TargetSource.
// Suppresses unnecessary default instantiation of the target bean:
// The TargetSource will handle target instances in a custom fashion.
TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
if (targetSource != null) {
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
//生成代理
return createProxy(beanClass, beanName, specificInterceptors, targetSource);
}
return null;
}
在createBean的代码中,我们可以看见这么一段:
populateBean(beanName, mergedBeanDefinition, instanceWrapper);
if (bean instanceof BeanNameAware) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking setBeanName on BeanNameAware bean '" + beanName + "'");
}
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanFactoryAware) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking setBeanFactory on BeanFactoryAware bean '" + beanName + "'");
}
((BeanFactoryAware) bean).setBeanFactory(this);
}
originalBean = bean;
bean = applyBeanPostProcessorsBeforeInitialization(bean, beanName);
invokeInitMethods(beanName, bean, mergedBeanDefinition);
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
在这个的代码中,我们可以清晰的看见Bean被实例化所要经过的一些过程;其中包括处理回调接口,调用init方法以及拦截器等等;
其次:
在最终的XmlBeanDefinition中:
public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
super(parentBeanFactory);
this.reader.loadBeanDefinitions(resource);
}
这个Reader.load()实际上是一个XML解析器,他的功能是把xml配置文件转换成为BeanDefinition存储到BeanFactory的
BeanDefinition map中去;
BeanFactory的类图结构,大量的采用模板模式,在顶级的抽象类中间约定了算法的实际流程,而把算法的具体实现方式等等推到了子类实现,从而可以扩展出多个功能的工厂