BeanDefinition 介绍
BeanDefinition是Bean的抽象表示,包括属性值,构造函数参数值及具体实现提供的更详细的的信息。BeanDefinition是一个最小Bean需要的接口,能够被BeanFactoryPostProcessor用来内审和修改原数据信息。先来看BeanDefinition的源码:
public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement {
String SCOPE_SINGLETON = ConfigurableBeanFactory.SCOPE_SINGLETON;
String SCOPE_PROTOTYPE = ConfigurableBeanFactory.SCOPE_PROTOTYPE;
int ROLE_APPLICATION = 0;
int ROLE_SUPPORT = 1;
int ROLE_INFRASTRUCTURE = 2;
//可修改属性
void setParentName(@Nullable String parentName);
String getParentName();
void setBeanClassName(@Nullable String beanClassName);
String getBeanClassName();
void setScope(@Nullable String scope);
String getScope();
void setLazyInit(boolean lazyInit);
boolean isLazyInit();
void setDependsOn(@Nullable String... dependsOn);
String[] getDependsOn();
void setAutowireCandidate(boolean autowireCandidate);
boolean isAutowireCandidate();
void setPrimary(boolean primary);
boolean isPrimary();
void setFactoryBeanName(@Nullable String factoryBeanName);
String getFactoryBeanName();
void setFactoryMethodName(@Nullable String factoryMethodName);
String getFactoryMethodName();
ConstructorArgumentValues getConstructorArgumentValues();
default boolean hasConstructorArgumentValues() {
return !getConstructorArgumentValues().isEmpty();
}
MutablePropertyValues getPropertyValues();
default boolean hasPropertyValues() {
return !getPropertyValues().isEmpty();
}
void setInitMethodName(@Nullable String initMethodName);
String getInitMethodName();
void setDestroyMethodName(@Nullable String destroyMethodName);
String getDestroyMethodName();
void setRole(int role);
int getRole();
void setDescription(@Nullable String description);
String getDescription();
// 只读属性
ResolvableType getResolvableType();
boolean isSingleton();
boolean isPrototype();
boolean isAbstract();
String getResourceDescription();
BeanDefinition getOriginatingBeanDefinition();
}
从接口定义中可以看到,接口定义主要分为以下几个模块:
1、接口定义:继承自 AttributeAccessor 和 BeanMetadataElement
2、常量定义: 对象SCOPE、对象角色
3、可修改属性:parentName 、beanClass、scope、lazyInit、dependsOn、autowireCandidate、primary、factoryBeanName、factoryMethodName、ConstructorArgumentValues、initMethodName、destoryMethodName、role、description
4、只读属性:singleton、prototype、abstract、resourceDescription、BeanDefinition
BeanMetadataElement介绍
BeanMetadataElement由携带配置源对象的bean元数据元素实现。主要包含获取源对象的方法:
public interface BeanMetadataElement {
default Object getSource() {
return null;
}
}
AttributeAccessor介绍
AttributeAccessor接口定义一个通用契约,用于向任意对象附加和访问元数据。具体源码如下:
public interface AttributeAccessor {
void setAttribute(String name, @Nullable Object value);
Object getAttribute(String name);
Object removeAttribute(String name);
boolean hasAttribute(String name);
String[] attributeNames();
}
BeanDefinition体系分析
我们看到BeanDefinition主要包括如下体系结构
其中常用的主要为ChildBeanDefinition 和 RootBeanDefinition。其中AnnotatedBeanDefinition主要是用于基于注解和扫描的情况。其中的实现类都比较简单,主要是一个属性的设置和获取方法,本文就不深入分析了。暂时了解到BeanDefinition是用于对Bean的描述抽象就好了。
注:不管是基于Java的配置,还是基于xml 或者基于Groovy的配置,最后都会通过BeanDefinition来抽象化表示。