Spring源码–BeanDefinition
通过读取spring官方参考文献,你就应该对spring有一个清晰的认知,对于ioc的地位的描述请看spring文献开篇内容
This part of the reference documentation covers all the technologies that are absolutely integral to the Spring Framework.
Foremost amongst these is the Spring Framework’s Inversion of Control (IoC) container. A thorough treatment of the Spring Framework’s IoC container is closely followed by comprehensive coverage of Spring’s Aspect-Oriented Programming (AOP) technologies.
参考文档的这一部分涵盖了Spring框架中绝对不可或缺的所有技术。
《其中最重要的是Spring Framework的控制反转(IoC)容器。对Spring框架的IoC容器进行全面处理之后》,对Spring的面向方面编程(AOP)技术的全面报道紧随其后。
从上面内容看ioc的功能重要程度是最重要,aop还要排在ioc后面。对于ioc学习先铺垫下一些核心内容,本次介绍BeanDefinition以及相关子类。
做什么用的?
这个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} 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
*/
翻译一下上面说的,大概是下面的意思,主要也就是说BeanDefinition是提供bean创建的相关信息,接下来我们见证下源码
Bean定义描述了一个bean实例,它具有属性值、构造函数参数值以及由具体实现提供的进一步信息。
BeanFactoryPostProcessor这只是一个最小的接口:主要的目的是允许来介绍和修改属性值和其他bean元数据。
源码
public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement {
// 单例、原型变量
String SCOPE_SINGLETON = ConfigurableBeanFactory.SCOPE_SINGLETON;
String SCOPE_PROTOTYPE = ConfigurableBeanFactory.SCOPE_PROTOTYPE;
// 通常对应于用户定义的 bean。
int ROLE_APPLICATION = 0;
//通常是外部配置
int ROLE_SUPPORT = 1;
//内部工作的 bean
int ROLE_INFRASTRUCTURE = 2;
// Modifiable attributes
void setParentName(@Nullable String parentName);
@Nullable
String getParentName();
//指定此 bean 定义的 bean 类名
void setBeanClassName(@Nullable String beanClassName);
@Nullable
String getBeanClassName();
//覆盖此 bean 的目标范围,指定一个新的范围名称
void setScope(@Nullable String scope);
@Nullable
String getScope();
//设置这个 bean 是否应该被延迟初始化
void setLazyInit(boolean lazyInit);
boolean isLazyInit();
//设置此 bean 初始化所依赖的 bean 的名称。 bean 工厂将保证这些 bean 首先被初始化。
void setDependsOn(@Nullable String... dependsOn);
@Nullable
String[] getDependsOn();
//设置此 bean 是否是自动装配到其他 bean 的候选对象。
void setAutowireCandidate(boolean autowireCandidate);
boolean isAutowireCandidate();
//设置此 bean 是否是主要的自动装配候选者。
void setPrimary(boolean primary);
boolean isPrimary();
......太长了,自己去源码看吧,主要是设置属性的set,get方法
}
相关类
在BeanDefinition源码中有两个父类BeanMetadataElement,AttributeAccessor,这个两个接口也没啥东西感兴趣,自己后面看下吧。主要解析下实现子类,下图是集成关系图。
从上面这个图可以看出来,BeanDefinition下主要有两个一个AnnotateBeanDefiniton和AbstractBeanDefinition两个类。这两个子类看名字猜下,应该能猜出来大致是做什么的。AnnotateBeanDefiniton主要做是处理注解bean的,AbstractBeanDefinition 已经对 BeanDefinition 方法有了基本实现逻辑的抽象类,增加了许多新的属性。