《深刻理解Spring系列之一:開篇》中提到在Spring容器啓動的過程當中,會將類解析成Spring內部的BeanDefinition結構,並將BeanDefinition存儲到一個叫DefaultListableBeanFactory中,本篇將深刻分析BeanFactory。bash
首先,看一下DefaultListableBeanFactory的類圖,
post
能夠看到DefaultListableBeanFactory間接實現了BeanFactory接口,先來分析一下這個BeanFactory,直接查看BeanFactory源代碼,ui
public interface BeanFactory {
String FACTORY_BEAN_PREFIX = "&";
Object getBean(String name) throws BeansException;
T getBean(String name, Class requiredType) throws BeansException;
T getBean(Class requiredType) throws BeansException;
Object getBean(String name, Object... args) throws BeansException;
T getBean(Class requiredType, Object... args) throws BeansException;
boolean containsBean(String name);
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String name, Class typeToMatch) throws NoSuchBeanDefinitionException;
Class getType(String name) throws NoSuchBeanDefinitionException;
String[] getAliases(String name);
}複製代碼
從接口中的方法名能夠很容易的理解每一個方法的意圖,最經常使用或者最多見的就是getBean方法,用於獲取Bean的實例。BeanFactory是用於訪問Spring Bean容器的根接口,是一個單純的Bean工廠,也就是常說的IOC容器的頂層定義,各類IOC容器是在其基礎上爲了知足不一樣需求而擴展的,包括常用的ApplicationContext。spa
DefaultListableBeanFactory是整個Bean加載的核心部分,是Spring註冊及加載Bean的默認實現。下面列出了DefaultListableBeanFactory源代碼中兩個重要的屬性,code
/** Map of bean definition objects, keyed by bean name */
private final Map beanDefinitionMap = new ConcurrentHashMap(256);
/** List of bean definition names, in registration order */
private volatile List beanDefinitionNames = new ArrayList(256);複製代碼
其中,bean的定義被解析成BeanDefinition,同時解析獲得beanName,將beanName和BeanDefinition存儲到beanDefinitionMap中,同時會將beanName存儲到beanDefinitionNames中。cdn
DefaultListableBeanFactory間接繼承DefaultSingletonBeanRegistry,DefaultSingletonBeanRegistry中有以下屬性,對象
/** Cache of singleton objects: bean name --> bean instance */
private final Map singletonObjects = new ConcurrentHashMap(256);複製代碼
singletonObjects用於存儲單例bean的實例,getBean方法就是從這個Map裏取實例對象。blog