spring-BeanFactory的各项实现

本文详细剖析了Spring框架中BeanFactory的实现结构,包括AbstractBeanFactory、AliasRegistry、SingletonBeanRegistry等关键组件的功能与实现细节,以及它们在bean管理与注入中的作用。
摘要由CSDN通过智能技术生成

咱们直接看一下AbstractBeanFactory的继承和实现结构:
继承结构大体描述一下:AbstractBeanFactory功能结构主要有两部分,1.实现了BeanFactory相关的功能,2.实现了别名,单列注册以及工厂支持.
BeanFactory相关接口前面已经描述过,这里不再重复,接下来看一下2)部分:
1.AliasRegistry别名注册

	//给指定的bean注册别名
	void registerAlias(String name, String alias);
	//移除别名
	void removeAlias(String alias);
	//别名判断
	boolean isAlias(String name);
	//获取所有的别名
	String[] getAliases(String name);

2.SimpleAliasRegistry别名注册的简单实现类,核心结构如下:

	//别名map,键是别名,值是name
	private final Map<String, String> aliasMap = new ConcurrentHashMap<>(16);

3.SingletonBeanRegistry单例bean注册支持

	void registerSingleton(String beanName, Object singletonObject);
	Object getSingleton(String beanName);
	boolean containsSingleton(String beanName);
	String[] getSingletonNames();
	int getSingletonCount();
	//注册单例的锁,同步对单例结构的更改
	Object getSingletonMutex();

4.DefaultSingletonBeanRegistry对单列注册的结构性实现
看一下核心结构:

/** Cache of singleton objects: bean name to bean instance. */所有的单列都存储在这个map中
	private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

	/** Cache of singleton factories: bean name to ObjectFactory. */单列对象的创建工厂
	private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

	/** Cache of early singleton objects: bean name to bean instance. */正在创建中的bean
	private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);

	/** Set of registered singletons, containing the bean names in registration order. */按注册顺序的所有注册beanname的集合
	private final Set<String> registeredSingletons = new LinkedHashSet<>(256);

	/** Names of beans that are currently in creation. */当前正在创建中的bean
	private final Set<String> singletonsCurrentlyInCreation =
			Collections.newSetFromMap(new ConcurrentHashMap<>(16));

	/** Names of beans currently excluded from in creation checks. */排除在创建检查之外的beanname
	private final Set<String> inCreationCheckExclusions =
			Collections.newSetFromMap(new ConcurrentHashMap<>(16));

	/** List of suppressed Exceptions, available for associating related causes. */
	@Nullable
	private Set<Exception> suppressedExceptions;

	/** Flag that indicates whether we're currently within destroySingletons. */
	private boolean singletonsCurrentlyInDestruction = false;

	/** Disposable bean instances: bean name to disposable instance. */需要执行destroy接口的bean的map
	private final Map<String, Object> disposableBeans = new LinkedHashMap<>();

	/** Map between containing bean names: bean name to Set of bean names that the bean contains. */描述了bean和内部bean之间关系
	private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<>(16);

	/** Map between dependent bean names: bean name to Set of dependent bean names. */描述了当前bean被那些bean依赖的关系
	private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<>(64);

	/** Map between depending bean names: bean name to Set of bean names for the bean's dependencies. */描述了bean和依赖bean之间的关系
	private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<>(64);

5.FactoryBeanRegistrySupport工厂支持bean
看一下核心结构:

/** Cache of singleton objects created by FactoryBeans: FactoryBean name to object. */
private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<>(16);

6.AbstractBeanFactory第一个带有BeanFactory结尾的抽象类,基本成型,先来了解一下他的核心结构:

/** Parent bean factory, for bean inheritance support. */垂直工程结构的支持
	@Nullable
	private BeanFactory parentBeanFactory;

	/** ClassLoader to resolve bean class names with, if necessary. */类加载器
	@Nullable
	private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

	/** ClassLoader to temporarily resolve bean class names with, if necessary. */一般在lwt中使用
	@Nullable
	private ClassLoader tempClassLoader;

	/** Whether to cache bean metadata or rather reobtain it for every access. */是否缓存bean的元数据,不缓存的话每次创建bean都会重新加载bean的定义
	private boolean cacheBeanMetadata = true;

	/** Resolution strategy for expressions in bean definition values. */表达式解析spel
	@Nullable
	private BeanExpressionResolver beanExpressionResolver;

	/** Spring ConversionService to use instead of PropertyEditors. */类型安全转换服务
	@Nullable
	private ConversionService conversionService;

	/** Custom PropertyEditorRegistrars to apply to the beans of this factory. */属性注册
	private final Set<PropertyEditorRegistrar> propertyEditorRegistrars = new LinkedHashSet<>(4);

	/** Custom PropertyEditors to apply to the beans of this factory. */定制的属性编辑器
	private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<>(4);

	/** A custom TypeConverter to use, overriding the default PropertyEditor mechanism. */类型转换
	@Nullable
	private TypeConverter typeConverter;

	/** String resolvers to apply e.g. to annotation attribute values. */值解析
	private final List<StringValueResolver> embeddedValueResolvers = new CopyOnWriteArrayList<>();

	/** BeanPostProcessors to apply in createBean. */各种BeanPostProcessor集合
	private final List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>();

	/** Indicates whether any InstantiationAwareBeanPostProcessors have been registered. */是否有实例化BeanPost后置处理器
	private volatile boolean hasInstantiationAwareBeanPostProcessors;

	/** Indicates whether any DestructionAwareBeanPostProcessors have been registered. */是否有DestructionAwareBeanPostProcessors 后置处理器
	private volatile boolean hasDestructionAwareBeanPostProcessors;

	/** Map from scope identifier String to corresponding Scope. */各种scope
	private final Map<String, Scope> scopes = new LinkedHashMap<>(8);

	/** Security context used when running with a SecurityManager. */
	@Nullable
	private SecurityContextProvider securityContextProvider;

	/** Map from bean name to merged RootBeanDefinition. */合并后的bean定义map
	private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap<>(256);

	/** Names of beans that have already been created at least once. */已经创建的bean的合集
	private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<>(256));

	/** Names of beans that are currently in creation. */正在创建的原型
	private final ThreadLocal<Object> prototypesCurrentlyInCreation =
			new NamedThreadLocal<>("Prototype beans currently in creation");

7.AutowireCapableBeanFactory可注入bean工厂

	<T> T createBean(Class<T> beanClass) throws BeansException;
	void autowireBean(Object existingBean) throws BeansException;
	Object configureBean(Object existingBean, String beanName) throws BeansException;
	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);
	<T> NamedBeanHolder<T> resolveNamedBean(Class<T> requiredType) 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;

}

讲一个bean工厂转换成,该结构后可以单独使用手动创建bean,自动注入字段等功能.

8.DefaultListableBeanFactory默认可枚举工厂,默认的ApplicationContext创建的就是这个对象,通过他可以
简单的描述一下他的结构:

/** Map from serialized id to factory instance. */
	private static final Map<String, Reference<DefaultListableBeanFactory>> serializableFactories =
			new ConcurrentHashMap<>(8);

	/** Optional id for this factory, for serialization purposes. */
	@Nullable
	private String serializationId;

	/** Whether to allow re-registration of a different definition with the same name. */
	private boolean allowBeanDefinitionOverriding = true;

	/** Whether to allow eager class loading even for lazy-init beans. */
	private boolean allowEagerClassLoading = true;

	/** Optional OrderComparator for dependency Lists and arrays. */
	@Nullable
	private Comparator<Object> dependencyComparator;

	/** Resolver to use for checking if a bean definition is an autowire candidate. */
	private AutowireCandidateResolver autowireCandidateResolver = new SimpleAutowireCandidateResolver();

	/** Map from dependency type to corresponding autowired value. */可解析的依赖
	private final Map<Class<?>, Object> resolvableDependencies = new ConcurrentHashMap<>(16);

	/** Map of bean definition objects, keyed by bean name. */bean定义表
	private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);

	/** Map of singleton and non-singleton bean names, keyed by dependency type. */
	private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64);

	/** Map of singleton-only bean names, keyed by dependency type. */
	private final Map<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap<>(64);

	/** List of bean definition names, in registration order. */
	private volatile List<String> beanDefinitionNames = new ArrayList<>(256);

	/** List of names of manually registered singletons, in registration order. */
	private volatile Set<String> manualSingletonNames = new LinkedHashSet<>(16);

	/** Cached array of bean definition names in case of frozen configuration. */
	@Nullable
	private volatile String[] frozenBeanDefinitionNames;

	/** Whether bean definition metadata may be cached for all beans. */
	private volatile boolean configurationFrozen = false;

9.BeanDefinitionRegistry接口,所有的bean的定义都是通过这里的api注入到beanfactory中,常见的有解析xml配置或注解配置,然后注入到bean工厂中,看一下他的接口视图:


	void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
			throws BeanDefinitionStoreException;

	
	void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;

	
	BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;

	
	boolean containsBeanDefinition(String beanName);

	
	String[] getBeanDefinitionNames();

	
	int getBeanDefinitionCount();

	boolean isBeanNameInUse(String beanName);

下一节,我们一起看一下ApplicationContext的结构,然后进行一些必要的实践,加深对运行过程中,各个结构如何协调工作,具体存储数据的视图.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值