Spring4源码解析:BeanDefinition架构及实现
一、架构图
首先共同看下总体的 Java Class Diagrams 图:
二、具体类实现
2.1 AttributeAccessor
接口定义了一个通用的可对任意对象获取、修改等操作元数据的附加契约。主要方法如下:
public interface AttributeAccessor {
void setAttribute(String name, Object value);
Object getAttribute(String name);
Object removeAttribute(String name);
boolean hasAttribute(String name);
String[] attributeNames();
}
2.2 AttributeAccessorSupport
抽象类,AttributeAccessor支持类,主要针对属性CRUD操作。
主要方法、属性如下:
public abstract class AttributeAccessorSupport implements AttributeAccessor, Serializable {
private final Map<String, Object> attributes = new LinkedHashMap<String, Object>(0);
@Override
public void setAttribute(String name, Object value)
@Override
public Object getAttribute(String name)
@Override
public Object removeAttribute(String name)
@Override
public boolean hasAttribute(String name)
@Override
public String[] attributeNames()
protected void copyAttributesFrom(AttributeAccessor source)
@Override
public boolean equals(Object other)
@Override
public int hashCode()
}
2.3 BeanMetadataElement
用于传输配置源对象(对象的确切类型将取决于所使用的配置机制),在配置源对象中可获取 bean 元数据元素。主要方法:
public interface BeanMetadataElement {
Object getSource();
}
2.4 BeanMetadataAttributeAccessor
为了追踪对象定义源,实现了BeanMetadataElement接口的getResource()方法也提供了 AttributeAccessorSupport 针对属性的增删改查。主要方法如下:
private Object source;
public void setSource(Object source)
@Override
public Object getSource()
public void addMetadataAttribute(BeanMetadataAttribute attribute)
//bean definition定义中属性键值对容器
public BeanMetadataAttribute getMetadataAttribute(String name)
@Override
public void setAttribute(String name, Object value)
@Override
public Object getAttribute(String name)
@Override
public Object removeAttribute(String name)
2.5 BeanDefinition
配置文件元素标签在容器中内部表示形式,一个BeanDefinition描述了一个bean的实例,包括属性值,构造方法参数值和继承自它的类的更多信息。
BeanDefinition仅仅是一个最简单的接口,主要功能是允许BeanFactoryPostProcessor,比如实现类 PropertyPlaceHolderConfigure 能够检索并修改属性值和别的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; //做为大量配置的一部分(支持、扩展类)
int ROLE_INFRASTRUCTURE = 2; //指内部工作的基础构造
String getParentName();
void setParentName(String parentName);
String getBeanClassName();
void setBeanClassName(String beanClassName);
String getFactoryBeanName();
void setFactoryBeanName(String factoryBeanName);
String getFactoryMethodName();
void setFactoryMethodName(String factoryMethodName);
String getScope();
void setScope(String scope);
boolean isLazyInit();
void setLazyInit(boolean lazyInit);
//获取依赖 bean name(详见depends-on属性用法)
String[] getDependsOn();
void setDependsOn(String... dependsOn);
//自动装配
boolean isAutowireCandidate();
void setAutowireCandidate(boolean autowireCandidate);
boolean isPrimary();
void setPrimary(boolean primary);
ConstructorArgumentValues getConstructorArgumentValues();
MutablePropertyValues getPropertyValues();
boolean isSingleton();
boolean isPrototype();
boolean isAbstract();
int getRole();
String getDescription();
String getResourceDescription();
BeanDefinition getOriginatingBeanDefinition();
}
2.6 AbstractBeanDefinition
配置文件元素标签在容器中内部表示形式,一个BeanDefinition描述了一个bean的实例,包括属性值,构造方法参数值和继承自它的类的更多信息。
BeanDefinition仅仅是一个最简单的接口,主要功能是允许BeanFactoryPostProcessor,比如实现类 PropertyPlaceHolderConfigure 能够检索并修改属性值和别的bean的元数据。
主要方法:
@SuppressWarnings("serial")
public abstract class AbstractBeanDefinition extends BeanMetadataAttributeAccessor
implements BeanDefinition, Cloneable {
//默认作用域singleton,单例
public static final String SCOPE_DEFAULT = "";
//不自动装配
public static final int AUTOWIRE_NO = AutowireCapableBeanFactory.AUTOWIRE_NO;
//按名称装配
public static final int AUTOWIRE_BY_NAME = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;
//按类型装配
public static final int AUTOWIRE_BY_TYPE = AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE;
//构造器装配
public static final int AUTOWIRE_CONSTRUCTOR = AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR;
//已过时,不赞成使用
@Deprecated
public static final int AUTOWIRE_AUTODETECT = AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT;
//依赖检查:无依赖
public static final int DEPENDENCY_CHECK_NONE = 0;
//依赖检查:对象间引用
public static final int DEPENDENCY_CHECK_OBJECTS = 1;
//依赖检查:会核对所有的原始类型和String类型的属性
public static final int DEPENDENCY_CHECK_SIMPLE = 2;
//依赖检查:所有属性
public static final int DEPENDENCY_CHECK_ALL = 3;
//bean标签中 destroyMethod=""
public static final String INFER_METHOD = "(inferred)";
private volatile Object beanClass;
private String scope = SCOPE_DEFAULT;
private boolean abstractFlag = false;
private boolean lazyInit = false;
private int autowireMode = AUTOWIRE_NO;
private int dependencyCheck = DEPENDENCY_CHECK_NONE;
private String[] dependsOn;
private boolean autowireCandidate = true;
private boolean primary = false;
private final Map<String, AutowireCandidateQualifier> qualifiers =
new LinkedHashMap<String, AutowireCandidateQualifier>(0);
private boolean nonPublicAccessAllowed = true;
private boolean lenientConstructorResolution = true;
private ConstructorArgumentValues constructorArgumentValues;
private MutablePropertyValues propertyValues;
private MethodOverrides methodOverrides = new MethodOverrides();
private String factoryBeanName;
private String factoryMethodName;
private String initMethodName;
private String destroyMethodName;
private boolean enforceInitMethod = true;
private boolean enforceDestroyMethod = true;
private boolean synthetic = false;
private int role = BeanDefinition.ROLE_APPLICATION;
private String description;
private Resource resource;
protected AbstractBeanDefinition() {
this(null, null);
}
protected AbstractBeanDefinition(ConstructorArgumentValues cargs, MutablePropertyValues pvs) {
setConstructorArgumentValues(cargs);
setPropertyValues(pvs);
}
//深复制一个原有的beandefinition
protected AbstractBeanDefinition(BeanDefinition original) {
setParentName(original.getParentName());
setBeanClassName(original.getBeanClassName());
setFactoryBeanName(original.getFactoryBeanName());
setFactoryMethodName(original.getFactoryMethodName());
setScope(original.getScope());
setAbstract(original.isAbstract());
setLazyInit(original.isLazyInit());
setRole(original.getRole());
setConstructorArgumentValues(new ConstructorArgumentValues(original.getConstructorArgumentValues()));
setPropertyValues(new MutablePropertyValues(original.getPropertyValues()));
setSource(original.getSource());
copyAttributesFrom(original);
if (original instanceof AbstractBeanDefinition) {
AbstractBeanDefinition originalAbd = (AbstractBeanDefinition) original;
if (originalAbd.hasBeanClass()) {
setBeanClass(originalAbd.getBeanClass());
}
setAutowireMode(originalAbd.getAutowireMode());
setDependencyCheck(originalAbd.getDependencyCheck());
setDependsOn(originalAbd.getDependsOn());
setAutowireCandidate(originalAbd.isAutowireCandidate());
copyQualifiersFrom(originalAbd);
setPrimary(originalAbd.isPrimary());
setNonPublicAccessAllowed(originalAbd.isNonPublicAccessAllowed());
setLenientConstructorResolution(originalAbd.isLenientConstructorResolution());
setInitMethodName(originalAbd.getInitMethodName());
setEnforceInitMethod(originalAbd.isEnforceInitMethod());
setDestroyMethodName(originalAbd.getDestroyMethodName());
setEnforceDestroyMethod(originalAbd.isEnforceDestroyMethod());
setMethodOverrides(new MethodOverrides(originalAbd.getMethodOverrides()));
setSynthetic(originalAbd.isSynthetic());
setResource(originalAbd.getResource());
}else {
setResourceDescription(original.getResourceDescription());
}
}
//覆盖当前BeanDefinition
public void overrideFrom(BeanDefinition other) {
if (StringUtils.hasLength(other.getBeanClassName())) {
setBeanClassName(other.getBeanClassName());
}
if (StringUtils.hasLength(other.getFactoryBeanName())) {
setFactoryBeanName(other.getFactoryBeanName());
}
if (StringUtils.hasLength(other.getFactoryMethodName())) {
setFactoryMethodName(other.getFactoryMethodName());
}
if (StringUtils.hasLength(other.getScope())) {
setScope(other.getScope());
}
setAbstract(other.isAbstract());
setLazyInit(other.isLazyInit());
setRole(other.getRole());
getConstructorArgumentValues().addArgumentValues(other.getConstructorArgumentValues());
getPropertyValues().addPropertyValues(other.getPropertyValues());
setSource(other.getSource());
copyAttributesFrom(other);
if (other instanceof AbstractBeanDefinition) {
AbstractBeanDefinition otherAbd = (AbstractBeanDefinition) other;
if (otherAbd.hasBeanClass()) {
setBeanClass(otherAbd.getBeanClass());
}
setAutowireCandidate(otherAbd.isAutowireCandidate());
setAutowireMode(otherAbd.getAutowireMode());
copyQualifiersFrom(otherAbd);
setPrimary(otherAbd.isPrimary());
setDependencyCheck(otherAbd.getDependencyCheck());
setDependsOn(otherAbd.getDependsOn());
setNonPublicAccessAllowed(otherAbd.isNonPublicAccessAllowed());
setLenientConstructorResolution(otherAbd.isLenientConstructorResolution());
if (StringUtils.hasLength(otherAbd.getInitMethodName())) {
setInitMethodName(otherAbd.getInitMethodName());
setEnforceInitMethod(otherAbd.isEnforceInitMethod());
}
if (StringUtils.hasLength(otherAbd.getDestroyMethodName())) {
setDestroyMethodName(otherAbd.getDestroyMethodName());
setEnforceDestroyMethod(otherAbd.isEnforceDestroyMethod());
}
getMethodOverrides().addOverrides(otherAbd.getMethodOverrides());
setSynthetic(otherAbd.isSynthetic());
setResource(otherAbd.getResource());
}
else {
setResourceDescription(other.getResourceDescription());
}
}
//将提供的默认值应用于此bean。
public void applyDefaults(BeanDefinitionDefaults defaults) {
setLazyInit(defaults.isLazyInit());
setAutowireMode(defaults.getAutowireMode());
setDependencyCheck(defaults.getDependencyCheck());
setInitMethodName(defaults.getInitMethodName());
setEnforceInitMethod(false);
setDestroyMethodName(defaults.getDestroyMethodName());
setEnforceDestroyMethod(false);
}
public boolean hasBeanClass() {
return (this.beanClass instanceof Class);
}
public void setBeanClass(Class<?> beanClass) {
this.beanClass = beanClass;
}
//若已经解析就返回这个包装类。
public Class<?> getBeanClass() throws IllegalStateException {
Object beanClassObject = this.beanClass;
if (beanClassObject == null) {
throw new IllegalStateException("No bean class specified on bean definition");
}
if (!(beanClassObject instanceof Class)) {
throw new IllegalStateException(
"Bean class name [" + beanClassObject + "] has not been resolved into an actual Class");
}
return (Class<?>) beanClassObject;
}
@Override
public void setBeanClassName(String beanClassName) {
this.beanClass = beanClassName;
}
@Override
public String getBeanClassName() {
Object beanClassObject = this.beanClass;
if (beanClassObject instanceof Class) {
return ((Class<?>) beanClassObject).getName();
}
else {
return (String) beanClassObject;
}
}
//解析类
public Class<?> resolveBeanClass(ClassLoader classLoader) throws ClassNotFoundException {
String className = getBeanClassName();
if (className == null) {
return null;
}
Class<?> resolvedClass = ClassUtils.forName(className, classLoader);
this.beanClass = resolvedClass;
return resolvedClass;
}
@Override
public void setScope(String scope) {
this.scope = scope;
}
@Override
public String getScope() {
return this.scope;
}
@Override
public boolean isSingleton() {
return SCOPE_SINGLETON.equals(scope) || SCOPE_DEFAULT.equals(scope);
}
@Override
public boolean isPrototype() {
return SCOPE_PROTOTYPE.equals(scope);
}
public void setAbstract(boolean abstractFlag) {
this.abstractFlag = abstractFlag;
}
@Override
public boolean isAbstract() {
return this.abstractFlag;
}
@Override
public void setLazyInit(boolean lazyInit) {
this.lazyInit = lazyInit;
}
@Override
public boolean isLazyInit() {
return this.lazyInit;
}
public void setAutowireMode(int autowireMode) {
this.autowireMode = autowireMode;
}
public int getAutowireMode() {
return this.autowireMode;
}
public int getResolvedAutowireMode() {
if (this.autowireMode == AUTOWIRE_AUTODETECT) {
// Work out whether to apply setter autowiring or constructor autowiring.
// If it has a no-arg constructor it's deemed to be setter autowiring,
// otherwise we'll try constructor autowiring.
Constructor<?>[] constructors = getBeanClass().getConstructors();
for (Constructor<?> constructor : constructors) {
if (constructor.getParameterTypes().length == 0) {
return AUTOWIRE_BY_TYPE;
}
}
return AUTOWIRE_CONSTRUCTOR;
}
else {
return this.autowireMode;
}
}
public void setDependencyCheck(int dependencyCheck) {
this.dependencyCheck = dependencyCheck;
}
public int getDependencyCheck() {
return this.dependencyCheck;
}
@Override
public void setDependsOn(String... dependsOn) {
this.dependsOn = dependsOn;
}
@Override
public String[] getDependsOn() {
return this.dependsOn;
}
@Override
public void setAutowireCandidate(boolean autowireCandidate) {
this.autowireCandidate = autowireCandidate;
}
@Override
public boolean isAutowireCandidate() {
return this.autowireCandidate;
}
@Override
public void setPrimary(boolean primary) {
this.primary = primary;
}
@Override
public boolean isPrimary() {
return this.primary;
}
public void addQualifier(AutowireCandidateQualifier qualifier) {
this.qualifiers.put(qualifier.getTypeName(), qualifier);
}
public boolean hasQualifier(String typeName) {
return this.qualifiers.keySet().contains(typeName);
}
public AutowireCandidateQualifier getQualifier(String typeName) {
return this.qualifiers.get(typeName);
}
public Set<AutowireCandidateQualifier> getQualifiers() {
return new LinkedHashSet<AutowireCandidateQualifier>(this.qualifiers.values());
}
public void copyQualifiersFrom(AbstractBeanDefinition source) {
Assert.notNull(source, "Source must not be null");
this.qualifiers.putAll(source.qualifiers);
}
//指定是否允许访问非公共构造函数和方法
public void setNonPublicAccessAllowed(boolean nonPublicAccessAllowed) {
this.nonPublicAccessAllowed = nonPublicAccessAllowed;
}
public boolean isNonPublicAccessAllowed() {
return this.nonPublicAccessAllowed;
}
//构造器宽松模式或非宽松模式。
public void setLenientConstructorResolution(boolean lenientConstructorResolution)
public boolean isLenientConstructorResolution()
//构造函数参数
public void setConstructorArgumentValues(ConstructorArgumentValues constructorArgumentValues)
@Override
public ConstructorArgumentValues getConstructorArgumentValues()
public boolean hasConstructorArgumentValues()
public void setPropertyValues(MutablePropertyValues propertyValues)
@Override
public MutablePropertyValues getPropertyValues()
public void setMethodOverrides(MethodOverrides methodOverrides)
public MethodOverrides getMethodOverrides()
@Override
public void setFactoryBeanName(String factoryBeanName)
@Override
public String getFactoryBeanName()
@Override
public void setFactoryMethodName(String factoryMethodName)
@Override
public String getFactoryMethodName()
public void setInitMethodName(String initMethodName)
public String getInitMethodName()
//InitMethod默认配置, 默认值false
public void setEnforceInitMethod(boolean enforceInitMethod)
public boolean isEnforceInitMethod()
public void setDestroyMethodName(String destroyMethodName)
public String getDestroyMethodName()
//DestroyMethod默认配置, 默认值false
public void setEnforceDestroyMethod(boolean enforceDestroyMethod)
public boolean isEnforceDestroyMethod()
//一个合成的beandefinition
public void setSynthetic(boolean synthetic)
public boolean isSynthetic()
public void setRole(int role)
@Override
public int getRole()
public void setDescription(String description)
@Override
public String getDescription()
public void setResource(Resource resource)
public Resource getResource()
public void setResourceDescription(String resourceDescription)
@Override
public String getResourceDescription()
public void setOriginatingBeanDefinition(BeanDefinition originatingBd)
@Override
public BeanDefinition getOriginatingBeanDefinition()
public void validate() throws BeanDefinitionValidationException
//校验这个bean定义的需要覆盖的方面
public void prepareMethodOverrides() throws BeanDefinitionValidationException
//验证覆盖的方法
protected void prepareMethodOverride(MethodOverride mo) throws BeanDefinitionValidationException
//覆写Object的clone() */
@Override
public Object clone()
public abstract AbstractBeanDefinition cloneBeanDefinition();
@Override
public boolean equals(Object other)
@Override
public int hashCode()
@Override
public String toString()
}
2.7 AnnotatedBeanDefinition
public interface AnnotatedBeanDefinition extends BeanDefinition {
//获取该bean definition的注解元数据。
AnnotationMetadata getMetadata();
//获取该bean definition的注解元数据。
MethodMetadata getFactoryMethodMetadata();
}
2.8 RootBeanDefinition
RootBeanDefinition用来在配置阶段进行注册bean definition。
表明它是一个可合并的bean definition,即在spring beanFactory运行期间,可以返回一个特定的bean。RootBeanDefinition作为一个重要的通用的bean definition 视图。但在spring 4后,有的更好的选择:GenericBeanDefinition。
public class RootBeanDefinition extends AbstractBeanDefinition {
boolean allowCaching = true;
private BeanDefinitionHolder decoratedDefinition;
private volatile Class<?> targetType;
boolean isFactoryMethodUnique = false;
final Object constructorArgumentLock = new Object();
Object resolvedConstructorOrFactoryMethod;
volatile Class<?> resolvedFactoryMethodReturnType;
boolean constructorArgumentsResolved = false;
Object[] resolvedConstructorArguments;
Object[] preparedConstructorArguments;
final Object postProcessingLock = new Object();
boolean postProcessed = false;
volatile Boolean beforeInstantiationResolved;
private Set<Member> externallyManagedConfigMembers;
private Set<String> externallyManagedInitMethods;
private Set<String> externallyManagedDestroyMethods;
public RootBeanDefinition() {
super();
}
//创建一个单例的RootBeanDefinition
public RootBeanDefinition(Class<?> beanClass) {
super();
setBeanClass(beanClass);
}
public RootBeanDefinition(Class<?> beanClass, int autowireMode, boolean dependencyCheck) {
super();
setBeanClass(beanClass);
setAutowireMode(autowireMode);
if (dependencyCheck && getResolvedAutowireMode() != AUTOWIRE_CONSTRUCTOR) {
setDependencyCheck(RootBeanDefinition.DEPENDENCY_CHECK_OBJECTS);
}
}
public RootBeanDefinition(Class<?> beanClass, ConstructorArgumentValues cargs, MutablePropertyValues pvs) {
super(cargs, pvs);
setBeanClass(beanClass);
}
public RootBeanDefinition(String beanClassName) {
setBeanClassName(beanClassName);
}
public RootBeanDefinition(String beanClassName, ConstructorArgumentValues cargs, MutablePropertyValues pvs) {
super(cargs, pvs);
setBeanClassName(beanClassName);
}
//创建RootBeanDefinition,深度复制参数中的bean definition
public RootBeanDefinition(RootBeanDefinition original) {
super(original);
this.allowCaching = original.allowCaching;
this.decoratedDefinition = original.decoratedDefinition;
this.targetType = original.targetType;
this.isFactoryMethodUnique = original.isFactoryMethodUnique;
}
RootBeanDefinition(BeanDefinition original) {
super(original);
}
@Override
public String getParentName() {
return null;
}
@Override
public void setParentName(String parentName) {
if (parentName != null) {
throw new IllegalArgumentException("Root bean cannot be changed into a child bean with parent reference");
}
}
public void setDecoratedDefinition(BeanDefinitionHolder decoratedDefinition) {
this.decoratedDefinition = decoratedDefinition;
}
public BeanDefinitionHolder getDecoratedDefinition() {
return this.decoratedDefinition;
}
public void setTargetType(Class<?> targetType) {
this.targetType = targetType;
}
public Class<?> getTargetType() {
return this.targetType;
}
//指定一个工厂方法的名称,唯一、无重载的
public void setUniqueFactoryMethodName(String name) {
Assert.hasText(name, "Factory method name must not be empty");
setFactoryMethodName(name);
this.isFactoryMethodUnique = true;
}
//检查参数方法是能成为factory method
public boolean isFactoryMethod(Method candidate) {
return (candidate != null && candidate.getName().equals(getFactoryMethodName()));
}
//返回解析后的工厂方法作为Java对象方法,如果可用。
public Method getResolvedFactoryMethod() {
synchronized (this.constructorArgumentLock) {
Object candidate = this.resolvedConstructorOrFactoryMethod;
return (candidate instanceof Method ? (Method) candidate : null);
}
}
public void registerExternallyManagedConfigMember(Member configMember) {
synchronized (this.postProcessingLock) {
if (this.externallyManagedConfigMembers == null) {
this.externallyManagedConfigMembers = new HashSet<Member>(1);
}
this.externallyManagedConfigMembers.add(configMember);
}
}
public boolean isExternallyManagedConfigMember(Member configMember) {
synchronized (this.postProcessingLock) {
return (this.externallyManagedConfigMembers != null &&
this.externallyManagedConfigMembers.contains(configMember));
}
}
public void registerExternallyManagedInitMethod(String initMethod) {
synchronized (this.postProcessingLock) {
if (this.externallyManagedInitMethods == null) {
this.externallyManagedInitMethods = new HashSet<String>(1);
}
this.externallyManagedInitMethods.add(initMethod);
}
}
public boolean isExternallyManagedInitMethod(String initMethod) {
synchronized (this.postProcessingLock) {
return (this.externallyManagedInitMethods != null &&
this.externallyManagedInitMethods.contains(initMethod));
}
}
public void registerExternallyManagedDestroyMethod(String destroyMethod) {
synchronized (this.postProcessingLock) {
if (this.externallyManagedDestroyMethods == null) {
this.externallyManagedDestroyMethods = new HashSet<String>(1);
}
this.externallyManagedDestroyMethods.add(destroyMethod);
}
}
public boolean isExternallyManagedDestroyMethod(String destroyMethod) {
synchronized (this.postProcessingLock) {
return (this.externallyManagedDestroyMethods != null &&
this.externallyManagedDestroyMethods.contains(destroyMethod));
}
}
@Override
public RootBeanDefinition cloneBeanDefinition() {
return new RootBeanDefinition(this);
}
@Override
public boolean equals(Object other) {
return (this == other || (other instanceof RootBeanDefinition && super.equals(other)));
}
@Override
public String toString() {
return "Root bean: " + super.toString();
}
}
2.9 ConfigurationClassBeanDefinition
是ConfigurationClassBeanDefinitionReader的内部类,ConfigurationClassBeanDefinitionReader读取一组完全填充了属性的配置实例,通过context内给定的BeanDefinitionRegistry进行注册bean definition。
private static class ConfigurationClassBeanDefinition extends RootBeanDefinition implements AnnotatedBeanDefinition {
private final AnnotationMetadata annotationMetadata;
private final MethodMetadata factoryMethodMetadata;
public ConfigurationClassBeanDefinition(ConfigurationClass configClass, MethodMetadata beanMethodMetadata) {
this.annotationMetadata = configClass.getMetadata();
this.factoryMethodMetadata = beanMethodMetadata;
setLenientConstructorResolution(false);
}
public ConfigurationClassBeanDefinition(
RootBeanDefinition original, ConfigurationClass configClass, MethodMetadata beanMethodMetadata) {
super(original);
this.annotationMetadata = configClass.getMetadata();
this.factoryMethodMetadata = beanMethodMetadata;
}
private ConfigurationClassBeanDefinition(ConfigurationClassBeanDefinition original) {
super(original);
this.annotationMetadata = original.annotationMetadata;
this.factoryMethodMetadata = original.factoryMethodMetadata;
}
@Override
public AnnotationMetadata getMetadata() {
return this.annotationMetadata;
}
@Override
public MethodMetadata getFactoryMethodMetadata() {
return this.factoryMethodMetadata;
}
@Override
public boolean isFactoryMethod(Method candidate) {
return (super.isFactoryMethod(candidate) && BeanAnnotationHelper.isBeanAnnotated(candidate));
}
@Override
public ConfigurationClassBeanDefinition cloneBeanDefinition() {
return new ConfigurationClassBeanDefinition(this);
}
}
2.10 ChildBeanDefinition
public class ChildBeanDefinition extends AbstractBeanDefinition {
private String parentName;
//指定父类名称,创建子类。
public ChildBeanDefinition(String parentName) {
super();
this.parentName = parentName;
}
public ChildBeanDefinition(String parentName, MutablePropertyValues pvs) {
super(null, pvs);
this.parentName = parentName;
}
public ChildBeanDefinition(String parentName, ConstructorArgumentValues cargs, MutablePropertyValues pvs) {
super(cargs, pvs);
this.parentName = parentName;
}
public ChildBeanDefinition(String parentName, Class<?> beanClass, ConstructorArgumentValues cargs, MutablePropertyValues pvs) {
super(cargs, pvs);
this.parentName = parentName;
setBeanClass(beanClass);
}
public ChildBeanDefinition(String parentName, String beanClassName, ConstructorArgumentValues cargs, MutablePropertyValues pvs) {
super(cargs, pvs);
this.parentName = parentName;
setBeanClassName(beanClassName);
}
public ChildBeanDefinition(ChildBeanDefinition original) {
super(original);
}
@Override
public void setParentName(String parentName) {
this.parentName = parentName;
}
@Override
public String getParentName() {
return this.parentName;
}
@Override
public void validate() throws BeanDefinitionValidationException {
super.validate();
if (this.parentName == null) {
throw new BeanDefinitionValidationException("'parentName' must be set in ChildBeanDefinition");
}
}
@Override
public AbstractBeanDefinition cloneBeanDefinition() {
return new ChildBeanDefinition(this);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof ChildBeanDefinition)) {
return false;
}
ChildBeanDefinition that = (ChildBeanDefinition) other;
return (ObjectUtils.nullSafeEquals(this.parentName, that.parentName) && super.equals(other));
}
@Override
public int hashCode() {
return ObjectUtils.nullSafeHashCode(this.parentName) * 29 + super.hashCode();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("Child bean with parent '");
sb.append(this.parentName).append("': ").append(super.toString());
return sb.toString();
}
}
2.11 GenericBeanDefinition
GenericBeanDefinition是通用的标准bean definition,除了具有指定类可选的构造参数值、属性参数或其它bean definition一样的特性外,还具有parenetName属性,这也意味着可以用来灵活设置parent bean definition。
GenericBeanDefinition的使用会越来越广,而ChildBeanDefinition很可能会被替代。
public class GenericBeanDefinition extends AbstractBeanDefinition {
private String parentName;
public GenericBeanDefinition() {
super();
}
//深度复制
public GenericBeanDefinition(BeanDefinition original) {
super(original);
}
@Override
public void setParentName(String parentName) {
this.parentName = parentName;
}
@Override
public String getParentName() {
return this.parentName;
}
@Override
public AbstractBeanDefinition cloneBeanDefinition() {
return new GenericBeanDefinition(this);
}
@Override
public boolean equals(Object other) {
return (this == other || (other instanceof GenericBeanDefinition && super.equals(other)));
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("Generic bean");
if (this.parentName != null) {
sb.append(" with parent '").append(this.parentName).append("'");
}
sb.append(": ").append(super.toString());
return sb.toString();
}
}
2.12 ScannedGenericBeanDefinition
基于asm的类解析器,是GenericBeanDefinition类的扩展,支持注解元数据,这种支持通过AnnotatedBeanDefinition接口实现。
@SuppressWarnings("serial")
public class ScannedGenericBeanDefinition extends GenericBeanDefinition implements AnnotatedBeanDefinition {
private final AnnotationMetadata metadata;
public ScannedGenericBeanDefinition(MetadataReader metadataReader) {
Assert.notNull(metadataReader, "MetadataReader must not be null");
this.metadata = metadataReader.getAnnotationMetadata();
setBeanClassName(this.metadata.getClassName());
}
@Override
public final AnnotationMetadata getMetadata() {
return this.metadata;
}
@Override
public MethodMetadata getFactoryMethodMetadata() {
return null;
}
}
2.13 AnnotatedGenericBeanDefinition
对应注解@Bean。
@SuppressWarnings("serial")
public class AnnotatedGenericBeanDefinition extends GenericBeanDefinition implements AnnotatedBeanDefinition {
private final AnnotationMetadata metadata;
private MethodMetadata factoryMethodMetadata;
public AnnotatedGenericBeanDefinition(Class<?> beanClass) {
setBeanClass(beanClass);
this.metadata = new StandardAnnotationMetadata(beanClass, true);
}
public AnnotatedGenericBeanDefinition(AnnotationMetadata metadata) {
Assert.notNull(metadata, "AnnotationMetadata must not be null");
if (metadata instanceof StandardAnnotationMetadata) {
setBeanClass(((StandardAnnotationMetadata) metadata).getIntrospectedClass());
} else {
setBeanClassName(metadata.getClassName());
}
this.metadata = metadata;
}
public AnnotatedGenericBeanDefinition(AnnotationMetadata metadata, MethodMetadata factoryMethodMetadata) {
this(metadata);
Assert.notNull(factoryMethodMetadata, "MethodMetadata must not be null");
setFactoryMethodName(factoryMethodMetadata.getMethodName());
this.factoryMethodMetadata = factoryMethodMetadata;
}
@Override
public final AnnotationMetadata getMetadata() {
return this.metadata;
}
@Override
public final MethodMetadata getFactoryMethodMetadata() {
return this.factoryMethodMetadata;
}
}
Spring4源码解析:BeanDefinition架构及实现的更多相关文章
- mybatis源码解析之架构理解
mybatis是一个非常优秀的开源orm框架,在大型的互联网公司,基本上都会用到,而像程序员的圣地-阿里虽然用的是自己开发的一套框架,但其核心思想也无外乎这些,因此,去一些大型互联网公司面试的时候,总 ...
- ReactiveCocoa v2.5 源码解析 之 架构总览
ReactiveCocoa 是一个 iOS 中的函数式响应式编程框架,它受 Functional Reactive Programming 的启发,是 Justin Spahr-Summers 和 J ...
- ReactiveCocoa_v2.5 源码解析之架构总览
ReactiveCocoa 是一个 iOS 中的函数式响应式编程框架,它受 Functional Reactive Programming 的启发,是 Justin Spahr-Summers 和 J ...
- mapbox.gl源码解析——基本架构与数据渲染流程
加载地图 Mapbox GL JS是一个JavaScript库,使用WebGL渲染交互式矢量瓦片地图和栅格瓦片地图.WebGL渲染意味着高性能,MapboxGL能够渲染大量的地图要素,拥有流畅的交互以 ...
- jmh源码解析-整体架构
我理解的jmh运行架构图 生成字节码,字节码负责维护测试的状态和调用被测试的方法 默认在fork的进程中进行测试,可以配置多个fork进程,以减少误差 通过线程池,提交每个迭代的测试任务,任务执行后, ...
- 2017.9.26JQuery源码解析一 架构与依赖
jq1.0: css选择符 事件处理 ajax交互 1.2.3: 引入数据缓存,解决循环引用与大数据保存问题 1.3. : 使用全新的选择器引擎sizzle,在各个浏览器下全面超越其他同类js ...
- SpringCloud服务调用源码解析汇总
相信我,你会收藏这篇文章的,本篇文章涉及Ribbon.Hystrix.Feign三个组件的源码解析 Ribbon架构剖析 这篇文章介绍了Ribbon的基础架构,也就是下图涉及到的6大组件: Ribbo ...
- jQuery整体架构源码解析(转载)
jQuery整体架构源码解析 最近一直在研读 jQuery 源码,初看源码一头雾水毫无头绪,真正静下心来细看写的真是精妙,让你感叹代码之美. 其结构明晰,高内聚.低耦合,兼具优秀的性能与便利的扩展性, ...
- jQuery整体架构源码解析
最近一直在研读 jQuery 源码,初看源码一头雾水毫无头绪,真正静下心来细看写的真是精妙,让你感叹代码之美. 其结构明晰,高内聚.低耦合,兼具优秀的性能与便利的扩展性,在浏览器的兼容性(功能缺陷.渐 ...
随机推荐
- Python: 矩阵与线性代数运算
需要执行矩阵和线性代数运算,比如矩阵乘法.寻找行列式.求解线性方程组等等. 矩阵类似于3.9 小节中数组对象,但是遵循线性代数的计算规则.下面的一个例子展示了矩阵的一些基本特性: >>&g ...
- nodejs+express工程 在npm install之后或使用npm install bootstrap命令安装bootstrap之后
nodejs+express工程 在npm install之后或使用npm install bootstrap命令安装bootstrap之后引入bootstrap文件 如果你的静态资源存放在多个目录下 ...
- stm32_CAN总线知识(转)
源: stm32_CAN总线知识
- 20145204 《Java程序设计》第四周学习总结
20145204 <Java程序设计>第四周学习总结 教材学习内容总结 继承 什么时候使用继承? 当多个类中出现重复定义的行为(即多个类中出现重复的代码)时,就把相同的程序代码提成为父类. ...
- 初识PHP(一)基础语法
一直准备学习PHP,结果前一段时间总是有事情,耽误了一阵子.现在赶快迎头赶上! 这个系列只是谈谈我对于PHP的一些看法,不是教程性质的.另外我是小白,只是写写随笔,大神求轻拍.本人学习过c .java ...
- XML_Qt_资料
1.QXmlQuery Class _ Qt XML Patterns 5.7.html http://doc.qt.io/qt-5/qxmlquery.html ZC: evaluateTo(QAb ...
- 单例模式(Singleton-Pattern)百媚生
1 动机 对于系统中的某些类来说,只有一个实例很重要,例如,一个系统中可以存在多个打印任务,但是只能有一个正在工作的任务;一个系统只能有一个窗口管理器或文件系统;一个系统只能有一个计时工具或ID(序号 ...
- hdu4289最小割
最近博客断更了一段时间啊,快期末了,先把这个专题搞完再说 最小割=最大流 拆点方法很重要,刚开始我拆点不对就wa了,然后改进后tle,应该是数组开小了,一改果然是 #include<map> ...
- Mybatis整合Spring -- typeAliasesPackage
Mybatis整合Spring 根据官方的说法,在ibatis3,也就是Mybatis3问世之前,Spring3的开发工作就已经完成了,所以Spring3中还是没有对Mybatis3的支持. 因此由M ...
- 235.236. Lowest Common Ancestor of a Binary (Search) Tree -- 最近公共祖先
235. Lowest Common Ancestor of a Binary Search Tree Given a binary search tree (BST), find the lowes ...