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

相关文章

Java编译生成多个.class文件的原理和作用

《Java编译生成多个.class文件的原理和作用》作为一名经验丰富的开发者,在Java项目中执行编译后,可能会发现一个.java源文件有时会产生多个.class文件,从技术实现层面详细剖析这一现象... 目录一、内部类机制与.class文件生成成员内部类(常规内部类)局部内部类(方法内部类)匿名内部类二、

SpringBoot实现数据库读写分离的3种方法小结

《SpringBoot实现数据库读写分离的3种方法小结》为了提高系统的读写性能和可用性,读写分离是一种经典的数据库架构模式,在SpringBoot应用中,有多种方式可以实现数据库读写分离,本文将介绍三... 目录一、数据库读写分离概述二、方案一:基于AbstractRoutingDataSource实现动态

使用Jackson进行JSON生成与解析的新手指南

《使用Jackson进行JSON生成与解析的新手指南》这篇文章主要为大家详细介绍了如何使用Jackson进行JSON生成与解析处理,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 核心依赖2. 基础用法2.1 对象转 jsON(序列化)2.2 JSON 转对象(反序列化)3.

Springboot @Autowired和@Resource的区别解析

《Springboot@Autowired和@Resource的区别解析》@Resource是JDK提供的注解,只是Spring在实现上提供了这个注解的功能支持,本文给大家介绍Springboot@... 目录【一】定义【1】@Autowired【2】@Resource【二】区别【1】包含的属性不同【2】@

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La

Java枚举类实现Key-Value映射的多种实现方式

《Java枚举类实现Key-Value映射的多种实现方式》在Java开发中,枚举(Enum)是一种特殊的类,本文将详细介绍Java枚举类实现key-value映射的多种方式,有需要的小伙伴可以根据需要... 目录前言一、基础实现方式1.1 为枚举添加属性和构造方法二、http://www.cppcns.co

Elasticsearch 在 Java 中的使用教程

《Elasticsearch在Java中的使用教程》Elasticsearch是一个分布式搜索和分析引擎,基于ApacheLucene构建,能够实现实时数据的存储、搜索、和分析,它广泛应用于全文... 目录1. Elasticsearch 简介2. 环境准备2.1 安装 Elasticsearch2.2 J

Java中的String.valueOf()和toString()方法区别小结

《Java中的String.valueOf()和toString()方法区别小结》字符串操作是开发者日常编程任务中不可或缺的一部分,转换为字符串是一种常见需求,其中最常见的就是String.value... 目录String.valueOf()方法方法定义方法实现使用示例使用场景toString()方法方法

Java中List的contains()方法的使用小结

《Java中List的contains()方法的使用小结》List的contains()方法用于检查列表中是否包含指定的元素,借助equals()方法进行判断,下面就来介绍Java中List的c... 目录详细展开1. 方法签名2. 工作原理3. 使用示例4. 注意事项总结结论:List 的 contain

Java实现文件图片的预览和下载功能

《Java实现文件图片的预览和下载功能》这篇文章主要为大家详细介绍了如何使用Java实现文件图片的预览和下载功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... Java实现文件(图片)的预览和下载 @ApiOperation("访问文件") @GetMapping("