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

相关文章

SpringBoot中四种AOP实战应用场景及代码实现

《SpringBoot中四种AOP实战应用场景及代码实现》面向切面编程(AOP)是Spring框架的核心功能之一,它通过预编译和运行期动态代理实现程序功能的统一维护,在SpringBoot应用中,AO... 目录引言场景一:日志记录与性能监控业务需求实现方案使用示例扩展:MDC实现请求跟踪场景二:权限控制与

Android实现定时任务的几种方式汇总(附源码)

《Android实现定时任务的几种方式汇总(附源码)》在Android应用中,定时任务(ScheduledTask)的需求几乎无处不在:从定时刷新数据、定时备份、定时推送通知,到夜间静默下载、循环执行... 目录一、项目介绍1. 背景与意义二、相关基础知识与系统约束三、方案一:Handler.postDel

Java NoClassDefFoundError运行时错误分析解决

《JavaNoClassDefFoundError运行时错误分析解决》在Java开发中,NoClassDefFoundError是一种常见的运行时错误,它通常表明Java虚拟机在尝试加载一个类时未能... 目录前言一、问题分析二、报错原因三、解决思路检查类路径配置检查依赖库检查类文件调试类加载器问题四、常见

Java注解之超越Javadoc的元数据利器详解

《Java注解之超越Javadoc的元数据利器详解》本文将深入探讨Java注解的定义、类型、内置注解、自定义注解、保留策略、实际应用场景及最佳实践,无论是初学者还是资深开发者,都能通过本文了解如何利用... 目录什么是注解?注解的类型内置注编程解自定义注解注解的保留策略实际用例最佳实践总结在 Java 编程

Java 实用工具类Spring 的 AnnotationUtils详解

《Java实用工具类Spring的AnnotationUtils详解》Spring框架提供了一个强大的注解工具类org.springframework.core.annotation.Annot... 目录前言一、AnnotationUtils 的常用方法二、常见应用场景三、与 JDK 原生注解 API 的

Java controller接口出入参时间序列化转换操作方法(两种)

《Javacontroller接口出入参时间序列化转换操作方法(两种)》:本文主要介绍Javacontroller接口出入参时间序列化转换操作方法,本文给大家列举两种简单方法,感兴趣的朋友一起看... 目录方式一、使用注解方式二、统一配置场景:在controller编写的接口,在前后端交互过程中一般都会涉及

Java中的StringBuilder之如何高效构建字符串

《Java中的StringBuilder之如何高效构建字符串》本文将深入浅出地介绍StringBuilder的使用方法、性能优势以及相关字符串处理技术,结合代码示例帮助读者更好地理解和应用,希望对大家... 目录关键点什么是 StringBuilder?为什么需要 StringBuilder?如何使用 St

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

Java并发编程之如何优雅关闭钩子Shutdown Hook

《Java并发编程之如何优雅关闭钩子ShutdownHook》这篇文章主要为大家详细介绍了Java如何实现优雅关闭钩子ShutdownHook,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起... 目录关闭钩子简介关闭钩子应用场景数据库连接实战演示使用关闭钩子的注意事项开源框架中的关闭钩子机制1.

Maven中引入 springboot 相关依赖的方式(最新推荐)

《Maven中引入springboot相关依赖的方式(最新推荐)》:本文主要介绍Maven中引入springboot相关依赖的方式(最新推荐),本文给大家介绍的非常详细,对大家的学习或工作具有... 目录Maven中引入 springboot 相关依赖的方式1. 不使用版本管理(不推荐)2、使用版本管理(推