从BeanDefinition到Bean实例
对比SimpleBeanDefinitionRegistry
和DefaultListableBeanFactory
的源码,中间省略一些无关紧要的逻辑:
SimpleBeanDefinitionRegistry.java
java
public class SimpleBeanDefinitionRegistry extends SimpleAliasRegistry implements BeanDefinitionRegistry {
/** Map of bean definition objects, keyed by bean name. */
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(64);
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
this.beanDefinitionMap.put(beanName, beanDefinition);
}
@Override
public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException {
BeanDefinition bd = this.beanDefinitionMap.get(beanName);
if (bd == null) {
throw new NoSuchBeanDefinitionException(beanName);
}
return bd;
}
}
DefaultListableBeanFactory.java
java
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
/** Map of bean definition objects, keyed by bean name. */
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
// 实现比较复杂暂时省略
}
@Override
public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException {
// 实现比较复杂暂时省略
}
@Override
public Object getBean(String name) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(name);
}
@Override
public <T> T getBean(Class<T> requiredType) throws BeansException {
return getBean(requiredType, (Object[]) null);
}
}
从类关系上来看DefaultListableBeanFactory
不单单实现了BeanDefinitionRegistry
,还实现了BeanFactory
(继承了AbstractAutowireCapableBeanFactory
)提供了获取bean实例的方法。分析其继承关系如下:
<<interface>> BeanDefinitionRegistry 注册BeanDefinition接口 <<interface>> BeanFactory ioc容器核心接口 <<interface>> ListableBeanFactory BeanFactory扩展,提供获取所有Bean的能力 <<interface>> AutowireCapableBeanFactory BeanFactory扩展,提供自动注入的能力 <<interface>> HierarchicalBeanFactory BeanFactory扩展,提供访问父容器的功能 <<interface>> ConfigurableBeanFactory 提供配置BeanFactory的能力 <<interface>> ConfigurableListableBeanFactory 提供配置、分析和修改bean定义,以及预实例化单例能力 DefaultListableBeanFactory Spring默认的BeanFactory实现
其中BeanFactory
是IOC容器的核心