目录
- BeanFactory体系类图
- 低级容器的常见接口、类
- 单例体系
- FactoryBean体系
- BeanFactory体系
- BeanFactory 容器的顶级接口
- ListableBeanFactory 可列单的BeanFactory
- HierarchicalBeanFactory 可分层的BeanFactory
- AutowireCapableBeanFactory 可自动装配的BeanFactory
- ConfigurableBeanFactory 包含常用配置的BeanFactory
- ConfigurableListableBeanFactory 整合BeanFactory体系的接口
- AbstractBeanFactory 提供了大量方法的实现
- AbstractAutowireCapableBeanFactory 提供自动装配的实现
- DefaultListableBeanFactory 功能齐全的最终实现类
- XmlBeanFactory 集成xml配置文件的解析
使用的spring源码版本 5.2.15.RELEASE
BeanFactory体系类图
白色的是接口,浅黄色的是实现类(包括抽象类)
低级容器的常见接口、类
在低级容器的接口中,ConfigurableListableBeanFactory 整合了BeanFactory体系的主要接口,功能齐全,声明|使用低级容器的接口时,一般都是使用此接口,高级容器中使用的低级容器接口就是ConfigurableListableBeanFactory。
在低级容器的实现类中,DefaultListableBeanFactory 是ConfigurableListableBeanFactory接口的直接实现类,并集成了低级容器的其它通用功能,功能齐全,是BeanFactory体系的主要实现类,高级容器中使用的低级容器实现一般也是 DefaultListableBeanFactory 。
低级容器在接口层面通常指的是 ConfigurableListableBeanFactory,在具体实现层面通常指的是 DefaultListableBeanFactory。
容器是一个抽象、泛化的概念,可以指 BeanFactory、ApplicationContext 体系的接口|类,也可以指这些类的实例,或者 DefaultListableBeanFactory 类中定义的用于存储 BeanDefinition、beanName、bean实例 的一系列集合。
单例体系
SingletonBeanRegistry 单例的顶级接口
SingletonBeanRegistry 定义了单例的通用操作
public interface SingletonBeanRegistry {
//注册单例
void registerSingleton(String beanName, Object singletonObject);
//获取单例
Object getSingleton(String beanName);
//判断是否包含指定的单例
boolean containsSingleton(String beanName);
//获取所有已注册(创建)的单例的name
String[] getSingletonNames();
//获取所有已注册(创建)的单例的数量
int getSingletonCount();
//获取单例注册表的互斥锁
Object getSingletonMutex();
}
主要方法有 registerSingleton()、getSingleton()
DefaultSingletonBeanRegistry 单例的主要实现类
DefaultSingletonBeanRegistry 是 SingletonBeanRegistry 接口的主要实现类,这个类需要关注3点
1、提供了一些集合类型的成员变量,主要是三级缓存、单例注册表
//一级缓存
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
//三级缓存
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
//二级缓存
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);
//单例注册表,元素是已创建的单例的name
private final Set<String> registeredSingletons = new LinkedHashSet<>(256);
2、registerSingleton()方法的实现
@Override
public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
Assert.notNull(beanName, "Bean name must not be null");
Assert.notNull(singletonObject, "Singleton object must not be null");
//如果一级缓存中没有对应实例,就调用addSingleton()添加创建好的实例
synchronized (this.singletonObjects) {
Object oldObject = this.singletonObjects.get(beanName);
if (oldObject != null) {
throw new IllegalStateException("Could not register object [" + singletonObject +
"] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
}
addSingleton(beanName, singletonObject);
}
}
//把创建好的单例放到一级缓存中,从二三级缓存中移除对应的实例,并在单例注册表中添加单例的beanName
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
所谓单例的注册,其实就是把创建好的单例放到一级缓存中,并在单例注册表中添加对应的beanName。
3、提供了2个getSingleton()方法
一个从三级缓存获取单例,一个从ObjectFactory获取单例,后者在创建好新实例后,会调用 addSingleton() 完成单例的注册。
FactoryBean体系
FactoryBean 从工厂获取目标实例
FactoryBean是spring提供的自定义获取bean实例的一种方式,FactoryBean本身会作为bean放到spring容器中,实质是以实例工厂的方式获取目标实例,默认以getObject()作为工厂方法,spring本身就有很多实例是通过FactoryBean方式获取的。
public interface FactoryBean<T> {
String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType";
//获取目标实例
T getObject() throws Exception;
//获取当前FactoryBean要创建的bean的java类型
Class<?> getObjectType();
/** 设置要创建的目标bean的scope是否是singleton,默认true
说明:FactoryBean本身的scope由所属的BeanFactory决定,通常是singleton */
default boolean isSingleton() {
return true;
}
}
FactoryBeanRegistrySupport 整合FactoryBean与单例
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {
/** 缓存FactoryBean实例创建的单例bean,如果创建的是原型bean实例,则不缓存。
key是FactoryBean实例的name,value是该FactoryBean实例创建的单例实例 */
private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<>(16);
//从缓存中获取目标bean实例
protected Object getCachedObjectForFactoryBean(String beanName) {
return this.factoryBeanObjectCache.get(beanName);
}
/** 从FactoryBean实例获取bean实例。
如果使用的FactoryBean是单例,且一级缓存中存在目标实例,则尝试从缓存(上面那个map)中获取目标实例;
否则调用doGetObjectFromFactoryBean()获取目标实例 */
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
if (factory.isSingleton() && containsSingleton(beanName)) {
synchronized (getSingletonMutex()) {
Object object = this.factoryBeanObjectCache.get(beanName);
if (object == null) {
object = doGetObjectFromFactoryBean(factory, beanName);
// Only post-process and store if not put there already during getObject() call above
// (e.g. because of circular reference processing triggered by custom getBean calls)
Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
if (alreadyThere != null) {
object = alreadyThere;
}
else {
if (shouldPostProcess) {
if (isSingletonCurrentlyInCreation(beanName)) {
// Temporarily return non-post-processed object, not storing it yet..
return object;
}
beforeSingletonCreation(beanName);
try {
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName,
"Post-processing of FactoryBean's singleton object failed", ex);
}
finally {
afterSingletonCreation(beanName);
}
}
if (containsSingleton(beanName)) {
this.factoryBeanObjectCache.put(beanName, object);
}
}
}
return object;
}
}
else {
Object object = doGetObjectFromFactoryBean(factory, beanName);
if (shouldPostProcess) {
try {
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
}
}
return object;
}
}
//doGetObjectFromFactoryBean()的实质是调用FactoryBean的getObject()方法获取实例
private Object doGetObjectFromFactoryBean(FactoryBean<?> factory, String beanName) throws BeanCreationException {
Object object;
try {
if (System.getSecurityManager() != null) {
AccessControlContext acc = getAccessControlContext();
try {
object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
object = factory.getObject();
}
}
catch (FactoryBeanNotInitializedException ex) {
throw new BeanCurrentlyInCreationException(beanName, ex.toString());
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
}
// Do not accept a null value for a FactoryBean that's not fully
// initialized yet: Many FactoryBeans just return null then.
if (object == null) {
if (isSingletonCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(
beanName, "FactoryBean which is currently in creation returned null from getObject");
}
object = new NullBean();
}
return object;
}
//...
}
BeanFactory、FactoryBean的区别
- BeanFactory是低级容器,是生产、管理bean的工厂
- FactoryBean是spring提供的自定义获取bean实例的一种方式,FactoryBean本身会作为bean放到spring容器中,实质是以实例工厂的方式获取目标实例,默认以getObject()作为工厂方法
BeanFactory体系
BeanFactory 容器的顶级接口
BeanFactory是容器的顶级接口,定义IoC容器的基础功能,包括bean的创建、装配、获取、管理
public interface BeanFactory {
/** FactoryBean的name前缀。
FactoryBean本身会作为bean放到容器中,假设这个FactoryBean的name是a,
则a访问的是这个FactoryBean实例的getObject()方法创建的bean实例,&a访问的才是这个FactoryBean实例本身 */
String FACTORY_BEAN_PREFIX = "&";
//获取指定名称的bean
Object getBean(String name) throws BeansException;
//获取指定名称、类型的bean
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
//获取指定类型的bean
<T> T getBean(Class<T> requiredType) throws BeansException;
//获取指定名称|类型的bean,并传递实参。实参会传给对应的构造方法或工厂方法
Object getBean(String name, Object... args) throws BeansException;
<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
//获取所需bean的提供者
<T> ObjectProvider<T> getBeanProvider(Class<T> requiredType);
<T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType);
//判断容器中是否有指定的bean
boolean containsBean(String name);
//判断bean是否是单例、原型模式
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
//判断bean是否和指定的类型匹配
boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException;
//获取bean对应的java类的Class对象
Class<?> getType(String name) throws NoSuchBeanDefinitionException;
Class<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException;
//根据bean的name获取对应的别名
String[] getAliases(String name);
}
主要定义了核心方法 getBean()
ListableBeanFactory 可列单的BeanFactory
Listable 即 list able 可列单的,可列举的。
ListableBeanFactory 可以看成在 BeanFactory 的基础上增加了容器中bean的清单,根据清单可以判断容器中是否有指定的bean、统计容器中bean的数量、获取满足要求的bean的名称、获取满足要求的所有的bean等。
public interface ListableBeanFactory extends BeanFactory {
//当前BeanFactory实例中是否包含指定bean的BeanDefinition
boolean containsBeanDefinition(String beanName);
//获取当前BeanFactory实例中的BeanDefinition数量
int getBeanDefinitionCount();
//获取当前BeanFactory实例中的所有bean(BeanDefinition)的名称
String[] getBeanDefinitionNames();
//获取指定bean对应的BeanProvider,allowEagerInit是单例的加载模式(饥饿加载还是懒加载)
<T> ObjectProvider<T> getBeanProvider(Class<T> requiredType, boolean allowEagerInit);
<T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType, boolean allowEagerInit);
//获取符合条件的所有bean的name,includeNonSingletons指定是否包含非单例模式(即原型模式)
String[] getBeanNamesForType(ResolvableType type);
String[] getBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit);
String[] getBeanNamesForType(@Nullable Class<?> type);
String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit);
//获取指定type的所有bean,返回map,key是bean实例的name,value是bean实例
<T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException;
<T> Map<String, T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException;
//获取指定注解的所有bean的name,eg. 获取@Controller注解标注的所有bean的name
String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType);
//获取指定注解的所有bean
Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException;
//获取指定bean对应的注解实例
<A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
throws NoSuchBeanDefinitionException;
}
HierarchicalBeanFactory 可分层的BeanFactory
public interface HierarchicalBeanFactory extends BeanFactory {
//获取 parent bean factory
BeanFactory getParentBeanFactory();
//判断当前BeanFactory实例中是否有指定名称的bean,只在当前bean factory中检索,不会在 parent bean factory 中检索
boolean containsLocalBean(String name);
}
hierarchical 分层的。
HierarchicalBeanFactory 在BeanFactory的基础上,允许BeanFactory具有层次、可分层,简单来说就是可继承其它的BeanFactory,支持父子上下文。
分层可以使容器的每层都专注于特定的层次,比如
WebApplicationContext -> ApplicationContext -> BeanFactory
BeanFactory 专注于提供容器的基础功能;ApplicationContext专注于提供容器的扩展功能,WebApplicationContext 专注于提供对web的支持。
AutowireCapableBeanFactory 可自动装配的BeanFactory
capable 有…能力的、允许…的、可以…的。
AutowireCapableBeanFactory 在 BeanFactory 的基础上,允许自动装配。
public interface AutowireCapableBeanFactory extends BeanFactory {
//自动装配的5种模式
int AUTOWIRE_NO = 0;
int AUTOWIRE_BY_NAME = 1;
int AUTOWIRE_BY_TYPE = 2;
int AUTOWIRE_CONSTRUCTOR = 3;
@Deprecated
int AUTOWIRE_AUTODETECT = 4;
String ORIGINAL_INSTANCE_SUFFIX = ".ORIGINAL";
//-------------------------------------------------------------------------
// Typical methods for creating and populating external bean instances
//-------------------------------------------------------------------------
<T> T createBean(Class<T> beanClass) throws BeansException;
void autowireBean(Object existingBean) throws BeansException;
Object configureBean(Object existingBean, String beanName) throws BeansException;
//-------------------------------------------------------------------------
// Specialized methods for fine-grained control over the bean lifecycle
//-------------------------------------------------------------------------
Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;
Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;
void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck)
throws BeansException;
void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException;
Object initializeBean(Object existingBean, String beanName) throws BeansException;
Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException;
Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException;
void destroyBean(Object existingBean);
//-------------------------------------------------------------------------
// Delegate methods for resolving injection points
//-------------------------------------------------------------------------
<T> NamedBeanHolder<T> resolveNamedBean(Class<T> requiredType) throws BeansException;
Object resolveBeanByName(String name, DependencyDescriptor descriptor) throws BeansException;
Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName) throws BeansException;
Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException;
}
主要定义了自动装配的模式、主要方法。
自动装配的5种模式 | 策略
- AUTOWIRE_NO:没有外部(xml配置文件)定义的自动装配、不进行自动装配,但BeanFactoryAware、注解驱动定义的注入仍然有效
- AUTOWIRE_BY_NAME:按照名称装配bean的属性,调用属性的setter方法进行注入
- AUTOWIRE_BY_TYPE:按照类型方式装配bean的属性,调用属性的setter方法进行注入
- AUTOWIRE_CONSTRUCTOR:使用构造方法进行装配。贪婪原则:优先选择使用参数个数多的构造方法,以注入更多的依赖。
- AUTOWIRE_AUTODETECT:自动选择合适的装配模式,spring官方不推荐
定义的主要方法
- resolveDependency() 解析依赖
- createBean() 创建bean实例
- configureBean() 配置bean
- initializeBean() 初始化bean,以及初始化过程中应用BeanPostProcessor要用到的2个方法applyBeanPostProcessorsBeforeInitialization()、applyBeanPostProcessorsAfterInitialization()
- destroyBean() 销毁bean
ConfigurableBeanFactory 包含常用配置的BeanFactory
ConfigurableBeanFactory接口 在 HierarchicalBeanFactory、SingletonBeanRegistry2个接口的基础上,定义了BeanFactory的通用配置。
extends SingletonBeanRegistry 是为了整合单例。
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
String SCOPE_SINGLETON = "singleton";
String SCOPE_PROTOTYPE = "prototype";
void setParentBeanFactory(BeanFactory parentBeanFactory) throws IllegalStateException;
void setBeanClassLoader(@Nullable ClassLoader beanClassLoader);
ClassLoader getBeanClassLoader();
void setTempClassLoader(@Nullable ClassLoader tempClassLoader);
ClassLoader getTempClassLoader();
void setCacheBeanMetadata(boolean cacheBeanMetadata);
boolean isCacheBeanMetadata();
void setBeanExpressionResolver(@Nullable BeanExpressionResolver resolver);
BeanExpressionResolver getBeanExpressionResolver();
void setConversionService(@Nullable ConversionService conversionService);
ConversionService getConversionService();
void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar);
void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass);
void copyRegisteredEditorsTo(PropertyEditorRegistry registry);
void setTypeConverter(TypeConverter typeConverter);
TypeConverter getTypeConverter();
void addEmbeddedValueResolver(StringValueResolver valueResolver);
boolean hasEmbeddedValueResolver();
String resolveEmbeddedValue(String value);
void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);
int getBeanPostProcessorCount();
void registerScope(String scopeName, Scope scope);
String[] getRegisteredScopeNames();
Scope getRegisteredScope(String scopeName);
void setApplicationStartup(ApplicationStartup applicationStartup);
ApplicationStartup getApplicationStartup();
AccessControlContext getAccessControlContext();
void copyConfigurationFrom(ConfigurableBeanFactory otherFactory);
void registerAlias(String beanName, String alias) throws BeanDefinitionStoreException;
void resolveAliases(StringValueResolver valueResolver);
BeanDefinition getMergedBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException;
void setCurrentlyInCreation(String beanName, boolean inCreation);
boolean isCurrentlyInCreation(String beanName);
void registerDependentBean(String beanName, String dependentBeanName);
String[] getDependentBeans(String beanName);
String[] getDependenciesForBean(String beanName);
void destroyBean(String beanName, Object beanInstance);
void destroyScopedBean(String beanName);
void destroySingletons();
}
ConfigurableListableBeanFactory 整合BeanFactory体系的接口
public interface ConfigurableListableBeanFactory
extends ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory {
void ignoreDependencyType(Class<?> type);
void ignoreDependencyInterface(Class<?> ifc);
void registerResolvableDependency(Class<?> dependencyType, @Nullable Object autowiredValue);
boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor)
throws NoSuchBeanDefinitionException;
BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
Iterator<String> getBeanNamesIterator();
void clearMetadataCache();
void freezeConfiguration();
boolean isConfigurationFrozen();
void preInstantiateSingletons() throws BeansException;
}
AbstractBeanFactory 提供了大量方法的实现
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
//...
}
这个抽象类实现了ConfigurableBeanFactory接口, ConfigurableBeanFactory -> HierarchicalBeanFactory -> BeanFactory,间接实现了HierarchicalBeanFactory、BeanFactory,即实现了BeanFactory的基本功能、分层、通用配置。
主要实现了 getBean() 方法、定义了createBean()方法。
AbstractAutowireCapableBeanFactory 提供自动装配的实现
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
//...
}
这个抽象类实现了 AutowireCapableBeanFactory 接口,提供了自动装配的实现,实现了DI。主要提供了doCreateBean()方法,实现了一系列createBean()方法。
包含了doCreateBean()中用到的方法,主要有
- createBeanInstance() 创建bean实例
- populateBean():填充属性,包括一系列autowired()方法
- initializeBean():初始化
DefaultListableBeanFactory 功能齐全的最终实现类
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
//...
}
DefaultListableBeanFactory是BeanFactory体系的最终实现类,整合了BeanFactory体系主要接口的功能,具有BeanFactory基本功能+可列单+分层+通用配置+自动装配+BeanDefinition处理的能力,功能齐全,一般都是使用DefaultListableBeanFactory作为基础容器的实现。
XmlBeanFactory 集成xml配置文件的解析
@Deprecated
public class XmlBeanFactory extends DefaultListableBeanFactory {
//...
}
只能解析单个xml配置文件,比较鸡肋,@Deprecated,基本不用。