Spring源码:BeanDefinition源码解析

2024-02-26 21:48

本文主要是介绍Spring源码:BeanDefinition源码解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

0. 前述

1. 类图

1. 1 BeanMetaData属性获取器

1.1.1 AttributeAccessor

1.1.2 BeanMetadataElement

1.1.3 AttributeAccessorSupport

1.1.4 BeanMetadataAttributeAccessor

1.1.5 BeanMetadataAttribute

1.2 BeanDefinition类图​​

1.2.1 BeanDefinition

1.2.2 AbstractBeanDefinition


0. 前述

本篇主要介绍下BeanDefinition类继承结构,以及其中涉及到的一些主要的类的源码分析;

1. 类图

1.1 BeanMetaData属性获取器

类继承结构如下:

这几个类主要存储了BeanDefinition的属性值,并为BeanDefinition提供了对属性值的增删改查等操作;

1.1.1 AttributeAccessor

/*** Interface defining a generic contract for attaching and accessing metadata* to/from arbitrary objects.** @author Rob Harrop* @since 2.0*/
public interface AttributeAccessor {/*** Set the attribute defined by {@code name} to the supplied	{@code value}.* If {@code value} is {@code null}, the attribute is {@link #removeAttribute removed}.* <p>In general, users should take care to prevent overlaps with other* metadata attributes by using fully-qualified names, perhaps using* class or package names as prefix.* @param name the unique attribute key* @param value the attribute value to be attached*/void setAttribute(String name, Object value);/*** Get the value of the attribute identified by {@code name}.* Return {@code null} if the attribute doesn't exist.* @param name the unique attribute key* @return the current value of the attribute, if any*/Object getAttribute(String name);/*** Remove the attribute identified by {@code name} and return its value.* Return {@code null} if no attribute under {@code name} is found.* @param name the unique attribute key* @return the last value of the attribute, if any*/Object removeAttribute(String name);/*** Return {@code true} if the attribute identified by {@code name} exists.* Otherwise return {@code false}.* @param name the unique attribute key*/boolean hasAttribute(String name);/*** Return the names of all attributes.*/String[] attributeNames();}

1.1.2 BeanMetadataElement

/*** Interface to be implemented by bean metadata elements* that carry a configuration source object.** @author Juergen Hoeller* @since 2.0*/
public interface BeanMetadataElement {/*** Return the configuration source {@code Object} for this metadata element* (may be {@code null}).*/Object getSource();}

1.1.3 AttributeAccessorSupport

/*** Support class for {@link AttributeAccessor AttributeAccessors}, providing* a base implementation of all methods. To be extended by subclasses.** <p>{@link Serializable} if subclasses and all attribute values are {@link Serializable}.** @author Rob Harrop* @author Juergen Hoeller* @since 2.0*/
@SuppressWarnings("serial")
public abstract class AttributeAccessorSupport implements AttributeAccessor, Serializable {/** Map with String keys and Object values */private final Map<String, Object> attributes = new LinkedHashMap<String, Object>(0);@Overridepublic void setAttribute(String name, Object value) {Assert.notNull(name, "Name must not be null");if (value != null) {this.attributes.put(name, value);}else {removeAttribute(name);}}@Overridepublic Object getAttribute(String name) {Assert.notNull(name, "Name must not be null");return this.attributes.get(name);}@Overridepublic Object removeAttribute(String name) {Assert.notNull(name, "Name must not be null");return this.attributes.remove(name);}@Overridepublic boolean hasAttribute(String name) {Assert.notNull(name, "Name must not be null");return this.attributes.containsKey(name);}@Overridepublic String[] attributeNames() {return StringUtils.toStringArray(this.attributes.keySet());}/*** Copy the attributes from the supplied AttributeAccessor to this accessor.* @param source the AttributeAccessor to copy from*/protected void copyAttributesFrom(AttributeAccessor source) {Assert.notNull(source, "Source must not be null");String[] attributeNames = source.attributeNames();for (String attributeName : attributeNames) {setAttribute(attributeName, source.getAttribute(attributeName));}}@Overridepublic boolean equals(Object other) {if (this == other) {return true;}if (!(other instanceof AttributeAccessorSupport)) {return false;}AttributeAccessorSupport that = (AttributeAccessorSupport) other;return this.attributes.equals(that.attributes);}@Overridepublic int hashCode() {return this.attributes.hashCode();}}

1.1.4 BeanMetadataAttributeAccessor

/*** Extension of {@link org.springframework.core.AttributeAccessorSupport},* holding attributes as {@link BeanMetadataAttribute} objects in order* to keep track of the definition source.** @author Juergen Hoeller* @since 2.5*/
@SuppressWarnings("serial")
public class BeanMetadataAttributeAccessor extends AttributeAccessorSupport implements BeanMetadataElement {private Object source;/*** Set the configuration source {@code Object} for this metadata element.* <p>The exact type of the object will depend on the configuration mechanism used.*/public void setSource(Object source) {this.source = source;}@Overridepublic Object getSource() {return this.source;}/*** Add the given BeanMetadataAttribute to this accessor's set of attributes.* @param attribute the BeanMetadataAttribute object to register*/public void addMetadataAttribute(BeanMetadataAttribute attribute) {super.setAttribute(attribute.getName(), attribute);}/*** Look up the given BeanMetadataAttribute in this accessor's set of attributes.* @param name the name of the attribute* @return the corresponding BeanMetadataAttribute object,* or {@code null} if no such attribute defined*/public BeanMetadataAttribute getMetadataAttribute(String name) {return (BeanMetadataAttribute) super.getAttribute(name);}@Overridepublic void setAttribute(String name, Object value) {super.setAttribute(name, new BeanMetadataAttribute(name, value));}@Overridepublic Object getAttribute(String name) {BeanMetadataAttribute attribute = (BeanMetadataAttribute) super.getAttribute(name);return (attribute != null ? attribute.getValue() : null);}@Overridepublic Object removeAttribute(String name) {BeanMetadataAttribute attribute = (BeanMetadataAttribute) super.removeAttribute(name);return (attribute != null ? attribute.getValue() : null);}}

1.1.5 BeanMetadataAttribute

/*** Holder for a key-value style attribute that is part of a bean definition.* Keeps track of the definition source in addition to the key-value pair.** @author Juergen Hoeller* @since 2.5*/
public class BeanMetadataAttribute implements BeanMetadataElement {private final String name;private final Object value;private Object source;/*** Create a new AttributeValue instance.* @param name the name of the attribute (never {@code null})* @param value the value of the attribute (possibly before type conversion)*/public BeanMetadataAttribute(String name, Object value) {Assert.notNull(name, "Name must not be null");this.name = name;this.value = value;}/*** Return the name of the attribute.*/public String getName() {return this.name;}/*** Return the value of the attribute.*/public Object getValue() {return this.value;}/*** Set the configuration source {@code Object} for this metadata element.* <p>The exact type of the object will depend on the configuration mechanism used.*/public void setSource(Object source) {this.source = source;}@Overridepublic Object getSource() {return this.source;}@Overridepublic boolean equals(Object other) {if (this == other) {return true;}if (!(other instanceof BeanMetadataAttribute)) {return false;}BeanMetadataAttribute otherMa = (BeanMetadataAttribute) other;return (this.name.equals(otherMa.name) &&ObjectUtils.nullSafeEquals(this.value, otherMa.value) &&ObjectUtils.nullSafeEquals(this.source, otherMa.source));}@Overridepublic int hashCode() {return this.name.hashCode() * 29 + ObjectUtils.nullSafeHashCode(this.value);}@Overridepublic String toString() {return "metadata attribute '" + this.name + "'";}
}

1.2 BeanDefinition类图

其中BeanDefinition依赖ConstructorArgumentValues和MutablePropertyValues,ConstructorArgumentValues用于存储构造函数所有的参数,MutablePropertyValues用于存储所有的属性值;

1.2.1 BeanDefinition

/*** A BeanDefinition describes a bean instance, which has property values,* constructor argument values, and further information supplied by* concrete implementations.** <p>This is just a minimal interface: The main intention is to allow a* {@link BeanFactoryPostProcessor} such as {@link PropertyPlaceholderConfigurer}* to introspect and modify property values and other bean metadata.** @author Juergen Hoeller* @author Rob Harrop* @since 19.03.2004* @see ConfigurableListableBeanFactory#getBeanDefinition* @see org.springframework.beans.factory.support.RootBeanDefinition* @see org.springframework.beans.factory.support.ChildBeanDefinition*/
public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement {/*** Scope identifier for the standard singleton scope: "singleton".* <p>Note that extended bean factories might support further scopes.* @see #setScope*/String SCOPE_SINGLETON = ConfigurableBeanFactory.SCOPE_SINGLETON;/*** Scope identifier for the standard prototype scope: "prototype".* <p>Note that extended bean factories might support further scopes.* @see #setScope*/String SCOPE_PROTOTYPE = ConfigurableBeanFactory.SCOPE_PROTOTYPE;/*** Role hint indicating that a {@code BeanDefinition} is a major part* of the application. Typically corresponds to a user-defined bean.*/int ROLE_APPLICATION = 0;/*** Role hint indicating that a {@code BeanDefinition} is a supporting* part of some larger configuration, typically an outer* {@link org.springframework.beans.factory.parsing.ComponentDefinition}.* {@code SUPPORT} beans are considered important enough to be aware* of when looking more closely at a particular* {@link org.springframework.beans.factory.parsing.ComponentDefinition},* but not when looking at the overall configuration of an application.*/int ROLE_SUPPORT = 1;/*** Role hint indicating that a {@code BeanDefinition} is providing an* entirely background role and has no relevance to the end-user. This hint is* used when registering beans that are completely part of the internal workings* of a {@link org.springframework.beans.factory.parsing.ComponentDefinition}.*/int ROLE_INFRASTRUCTURE = 2;// Modifiable attributes/*** Set the name of the parent definition of this bean definition, if any.*/void setParentName(String parentName);/*** Return the name of the parent definition of this bean definition, if any.*/String getParentName();/*** Specify the bean class name of this bean definition.* <p>The class name can be modified during bean factory post-processing,* typically replacing the original class name with a parsed variant of it.* @see #setParentName* @see #setFactoryBeanName* @see #setFactoryMethodName*/void setBeanClassName(String beanClassName);/*** Return the current bean class name of this bean definition.* <p>Note that this does not have to be the actual class name used at runtime, in* case of a child definition overriding/inheriting the class name from its parent.* Also, this may just be the class that a factory method is called on, or it may* even be empty in case of a factory bean reference that a method is called on.* Hence, do <i>not</i> consider this to be the definitive bean type at runtime but* rather only use it for parsing purposes at the individual bean definition level.* @see #getParentName()* @see #getFactoryBeanName()* @see #getFactoryMethodName()*/String getBeanClassName();/*** Override the target scope of this bean, specifying a new scope name.* @see #SCOPE_SINGLETON* @see #SCOPE_PROTOTYPE*/void setScope(String scope);/*** Return the name of the current target scope for this bean,* or {@code null} if not known yet.*/String getScope();/*** Set whether this bean should be lazily initialized.* <p>If {@code false}, the bean will get instantiated on startup by bean* factories that perform eager initialization of singletons.*/void setLazyInit(boolean lazyInit);/*** Return whether this bean should be lazily initialized, i.e. not* eagerly instantiated on startup. Only applicable to a singleton bean.*/boolean isLazyInit();/*** Set the names of the beans that this bean depends on being initialized.* The bean factory will guarantee that these beans get initialized first.*/void setDependsOn(String... dependsOn);/*** Return the bean names that this bean depends on.*/String[] getDependsOn();/*** Set whether this bean is a candidate for getting autowired into some other bean.* <p>Note that this flag is designed to only affect type-based autowiring.* It does not affect explicit references by name, which will get resolved even* if the specified bean is not marked as an autowire candidate. As a consequence,* autowiring by name will nevertheless inject a bean if the name matches.*/void setAutowireCandidate(boolean autowireCandidate);/*** Return whether this bean is a candidate for getting autowired into some other bean.*/boolean isAutowireCandidate();/*** Set whether this bean is a primary autowire candidate.* <p>If this value is {@code true} for exactly one bean among multiple* matching candidates, it will serve as a tie-breaker.*/void setPrimary(boolean primary);/*** Return whether this bean is a primary autowire candidate.*/boolean isPrimary();/*** Specify the factory bean to use, if any.* This the name of the bean to call the specified factory method on.* @see #setFactoryMethodName*/void setFactoryBeanName(String factoryBeanName);/*** Return the factory bean name, if any.*/String getFactoryBeanName();/*** Specify a factory method, if any. This method will be invoked with* constructor arguments, or with no arguments if none are specified.* The method will be invoked on the specified factory bean, if any,* or otherwise as a static method on the local bean class.* @see #setFactoryBeanName* @see #setBeanClassName*/void setFactoryMethodName(String factoryMethodName);/*** Return a factory method, if any.*/String getFactoryMethodName();/*** Return the constructor argument values for this bean.* <p>The returned instance can be modified during bean factory post-processing.* @return the ConstructorArgumentValues object (never {@code null})*/ConstructorArgumentValues getConstructorArgumentValues();/*** Return the property values to be applied to a new instance of the bean.* <p>The returned instance can be modified during bean factory post-processing.* @return the MutablePropertyValues object (never {@code null})*/MutablePropertyValues getPropertyValues();// Read-only attributes/*** Return whether this a <b>Singleton</b>, with a single, shared instance* returned on all calls.* @see #SCOPE_SINGLETON*/boolean isSingleton();/*** Return whether this a <b>Prototype</b>, with an independent instance* returned for each call.* @since 3.0* @see #SCOPE_PROTOTYPE*/boolean isPrototype();/*** Return whether this bean is "abstract", that is, not meant to be instantiated.*/boolean isAbstract();/*** Get the role hint for this {@code BeanDefinition}. The role hint* provides the frameworks as well as tools with an indication of* the role and importance of a particular {@code BeanDefinition}.* @see #ROLE_APPLICATION* @see #ROLE_SUPPORT* @see #ROLE_INFRASTRUCTURE*/int getRole();/*** Return a human-readable description of this bean definition.*/String getDescription();/*** Return a description of the resource that this bean definition* came from (for the purpose of showing context in case of errors).*/String getResourceDescription();/*** Return the originating BeanDefinition, or {@code null} if none.* Allows for retrieving the decorated bean definition, if any.* <p>Note that this method returns the immediate originator. Iterate through the* originator chain to find the original BeanDefinition as defined by the user.*/BeanDefinition getOriginatingBeanDefinition();
}

1.2.2 AbstractBeanDefinition

AbstractBeanDefinition定义了子类GenericBeanDefinition、RootBeanDefinition和ChildBeanDefinition公共的属性;

这篇关于Spring源码:BeanDefinition源码解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/750265

相关文章

JavaScript中的isTrusted属性及其应用场景详解

《JavaScript中的isTrusted属性及其应用场景详解》在现代Web开发中,JavaScript是构建交互式应用的核心语言,随着前端技术的不断发展,开发者需要处理越来越多的复杂场景,例如事件... 目录引言一、问题背景二、isTrusted 属性的来源与作用1. isTrusted 的定义2. 为

Java循环创建对象内存溢出的解决方法

《Java循环创建对象内存溢出的解决方法》在Java中,如果在循环中不当地创建大量对象而不及时释放内存,很容易导致内存溢出(OutOfMemoryError),所以本文给大家介绍了Java循环创建对象... 目录问题1. 解决方案2. 示例代码2.1 原始版本(可能导致内存溢出)2.2 修改后的版本问题在

Java CompletableFuture如何实现超时功能

《JavaCompletableFuture如何实现超时功能》:本文主要介绍实现超时功能的基本思路以及CompletableFuture(之后简称CF)是如何通过代码实现超时功能的,需要的... 目录基本思路CompletableFuture 的实现1. 基本实现流程2. 静态条件分析3. 内存泄露 bug

Java中Object类的常用方法小结

《Java中Object类的常用方法小结》JavaObject类是所有类的父类,位于java.lang包中,本文为大家整理了一些Object类的常用方法,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. public boolean equals(Object obj)2. public int ha

Go中sync.Once源码的深度讲解

《Go中sync.Once源码的深度讲解》sync.Once是Go语言标准库中的一个同步原语,用于确保某个操作只执行一次,本文将从源码出发为大家详细介绍一下sync.Once的具体使用,x希望对大家有... 目录概念简单示例源码解读总结概念sync.Once是Go语言标准库中的一个同步原语,用于确保某个操

SpringBoot项目中Maven剔除无用Jar引用的最佳实践

《SpringBoot项目中Maven剔除无用Jar引用的最佳实践》在SpringBoot项目开发中,Maven是最常用的构建工具之一,通过Maven,我们可以轻松地管理项目所需的依赖,而,... 目录1、引言2、Maven 依赖管理的基础概念2.1 什么是 Maven 依赖2.2 Maven 的依赖传递机

SpringBoot实现动态插拔的AOP的完整案例

《SpringBoot实现动态插拔的AOP的完整案例》在现代软件开发中,面向切面编程(AOP)是一种非常重要的技术,能够有效实现日志记录、安全控制、性能监控等横切关注点的分离,在传统的AOP实现中,切... 目录引言一、AOP 概述1.1 什么是 AOP1.2 AOP 的典型应用场景1.3 为什么需要动态插

Linux中shell解析脚本的通配符、元字符、转义符说明

《Linux中shell解析脚本的通配符、元字符、转义符说明》:本文主要介绍shell通配符、元字符、转义符以及shell解析脚本的过程,通配符用于路径扩展,元字符用于多命令分割,转义符用于将特殊... 目录一、linux shell通配符(wildcard)二、shell元字符(特殊字符 Meta)三、s

Java实现Excel与HTML互转

《Java实现Excel与HTML互转》Excel是一种电子表格格式,而HTM则是一种用于创建网页的标记语言,虽然两者在用途上存在差异,但有时我们需要将数据从一种格式转换为另一种格式,下面我们就来看看... Excel是一种电子表格格式,广泛用于数据处理和分析,而HTM则是一种用于创建网页的标记语言。虽然两

java图像识别工具类(ImageRecognitionUtils)使用实例详解

《java图像识别工具类(ImageRecognitionUtils)使用实例详解》:本文主要介绍如何在Java中使用OpenCV进行图像识别,包括图像加载、预处理、分类、人脸检测和特征提取等步骤... 目录前言1. 图像识别的背景与作用2. 设计目标3. 项目依赖4. 设计与实现 ImageRecogni