BeanDefinition
/**
* BeanDefinition 用于描述一个 bean 实例,包括属性值、构造参数和补充信息。
*/
public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement {
/**
* 标准单例 bean 的范围标识符
*/
String SCOPE_SINGLETON = ConfigurableBeanFactory.SCOPE_SINGLETON;
/**
* 标准多例 bean 的范围标识符
*/
String SCOPE_PROTOTYPE = ConfigurableBeanFactory.SCOPE_PROTOTYPE;
/**
* 此 bean 是应用程序的主要组成部分,通常对应于用户定义的 bean
*/
int ROLE_APPLICATION = 0;
/**
* 此 bean 是一些大型配置的支持部分
* {@link org.springframework.beans.factory.parsing.ComponentDefinition}.
*/
int ROLE_SUPPORT = 1;
/**
* 此 bean 与最终用户无关,是框架基础设施的一部分
*/
int ROLE_INFRASTRUCTURE = 2;
// Modifiable attributes
/**
* 设置此 BeanDefinition 的 parent
*/
void setParentName(@Nullable String parentName);
/**
* 读取此 BeanDefinition 的 parent
*/
@Nullable
String getParentName();
/**
* 设置此 BeanDefinition 关联的类名
*/
void setBeanClassName(@Nullable String beanClassName);
/**
* 读取此 BeanDefinition 关联的类名
*/
@Nullable
String getBeanClassName();
/**
* 设置此 BeanDefinition 的作用域
*/
void setScope(@Nullable String scope);
/**
* 读取此 BeanDefinition 的作用域
*/
@Nullable
String getScope();
/**
* 设置此 bean 的延迟初始化标识,单例、非抽象、非延迟初始化的 bean 将在启动时实例化
*/
void setLazyInit(boolean lazyInit);
/**
* 读取此 bean 的延迟初始化标识
*/
boolean isLazyInit();
/**
* 设置此 bean 依赖的其他 bean 名称【内部属性依赖】,
* BeanFactory 会保证其他依赖 bean 优先初始化
*/
void setDependsOn(@Nullable String... dependsOn);
/**
* 读取此 bean 依赖的其他 bean 名称
*/
@Nullable
String[] getDependsOn();
/**
* 设置此 bean 是否是依赖注入到其他 bean 的候选者
*/
void setAutowireCandidate(boolean autowireCandidate);
/**
* 读取此 bean 是否是依赖注入到其他 bean 的候选者
*/
boolean isAutowireCandidate();
/**
* 设置此 bean 是否是其他 bean 主要的依赖注入候选者【存在满足注入条件的多个 bean 时】
*/
void setPrimary(boolean primary);
/**
* 读取此 bean 是否是其他 bean 主要的依赖注入候选者
*/
boolean isPrimary();
/**
* 设置创建此 bean 的工厂 bean 名称【此 bean 是通过工厂 bean 创建的】
*/
void setFactoryBeanName(@Nullable String factoryBeanName);
/**
* 读取创建此 bean 的工厂 bean 名称
*/
@Nullable
String getFactoryBeanName();
/**
* 写入创建此 bean 的工厂方法,可传递构造函数
*/
void setFactoryMethodName(@Nullable String factoryMethodName);
/**
* 读取创建此 bean 的工厂方法
*/
@Nullable
String getFactoryMethodName();
/**
* 读取此 bean 的构造函数参数
*/
ConstructorArgumentValues getConstructorArgumentValues();
/**
* 此 bean 是否有构造函数参数
* @since 5.0.2
*/
default boolean hasConstructorArgumentValues() {
return !getConstructorArgumentValues().isEmpty();
}
/**
* 读取需要注入到此 bean 的属性列表【Dependency Injection】
*/
MutablePropertyValues getPropertyValues();
/**
* 此 bean 是否存在需要注入的属性列表
* @since 5.0.2
*/
default boolean hasPropertyValues() {
return !getPropertyValues().isEmpty();
}
/**
* 设置此 bean 的初始化方法名称
* @since 5.1
*/
void setInitMethodName(@Nullable String initMethodName);
/**
* 读取此 bean 的初始化方法名称
* @since 5.1
*/
@Nullable
String getInitMethodName();
/**
* 写入此 bean 的销毁方法名称
* @since 5.1
*/
void setDestroyMethodName(@Nullable String destroyMethodName);
/**
* 读取此 bean 的销毁方法名称
* Return the name of the destroy method.
* @since 5.1
*/
@Nullable
String getDestroyMethodName();
/**
* 写入此 bean 的角色
* @since 5.1
* @see #ROLE_APPLICATION
* @see #ROLE_SUPPORT
* @see #ROLE_INFRASTRUCTURE
*/
void setRole(int role);
/**
* 读取此 bean 的角色
*/
int getRole();
/**
* 写入此 bean 的描述信息
* @since 5.1
*/
void setDescription(@Nullable String description);
/**
* 读取此 bean 的描述信息
*/
@Nullable
String getDescription();
// Read-only attributes
/**
* 此 bean 是否是可共享的单例
*/
boolean isSingleton();
/**
* 此 bean 是否是多例
*/
boolean isPrototype();
/**
* 此 bean 是否是抽象的,不能实例化
*/
boolean isAbstract();
/**
* 此 BeanDefinition 的来源
*/
@Nullable
String getResourceDescription();
/**
* 读取原始的 BeanDefinition,未加装饰
*/
@Nullable
BeanDefinition getOriginatingBeanDefinition();
}
- AbstractBeanDefinition:BeanDefinition 接口的核心实现
/**
* 羽翼丰满的 BeanDefinition 基础类
*/
@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;
/**
* 此 bean 不需要执行依赖检查
*/
public static final int DEPENDENCY_CHECK_NONE = 0;
/**
* 此 bean 需要执行对象引用的依赖检查
*/
public static final int DEPENDENCY_CHECK_OBJECTS = 1;
/**
* 此 bean 需要执行简单属性的依赖检查
*/
public static final int DEPENDENCY_CHECK_SIMPLE = 2;
/**
* 此 bean 需要对所有属性执行依赖检查
*/
public static final int DEPENDENCY_CHECK_ALL = 3;
/**
* 此 bean 需要自动推断销毁方法的名称
*/
public static final String INFER_METHOD = "(inferred)";
@Nullable
private volatile Object beanClass;
@Nullable
private String scope = SCOPE_DEFAULT;
private boolean abstractFlag = false;
private boolean lazyInit = false;
private int autowireMode = AUTOWIRE_NO;
private int dependencyCheck = DEPENDENCY_CHECK_NONE;
@Nullable
private String[] dependsOn;
private boolean autowireCandidate = true;
private boolean primary = false;
private final Map<String, AutowireCandidateQualifier> qualifiers = new LinkedHashMap<>();
/**
* 实例生成器
*/
@Nullable
private Supplier<?> instanceSupplier;
private boolean nonPublicAccessAllowed = true;
private boolean lenientConstructorResolution = true;
@Nullable
private String factoryBeanName;
@Nullable
private String factoryMethodName;
@Nullable
private ConstructorArgumentValues constructorArgumentValues;
@Nullable
private MutablePropertyValues propertyValues;
@Nullable
private MethodOverrides methodOverrides;
@Nullable
private String initMethodName;
@Nullable
private String destroyMethodName;
/**
* 强制执行初始化方法
*/
private boolean enforceInitMethod = true;
/**
* 强制执行销毁方法
*/
private boolean enforceDestroyMethod = true;
/**
* 此 bean 是否是合成的
*/
private boolean synthetic = false;
private int role = BeanDefinition.ROLE_APPLICATION;
@Nullable
private String description;
@Nullable
private Resource resource;
protected AbstractBeanDefinition() {
this(null, null);
}
protected AbstractBeanDefinition(@Nullable ConstructorArgumentValues cargs, @Nullable MutablePropertyValues pvs) {
constructorArgumentValues = cargs;
propertyValues = pvs;
}
protected AbstractBeanDefinition(BeanDefinition original) {
setParentName(original.getParentName());
setBeanClassName(original.getBeanClassName());
setScope(original.getScope());
setAbstract(original.isAbstract());
setLazyInit(original.isLazyInit());
setFactoryBeanName(original.getFactoryBeanName());
setFactoryMethodName(original.getFactoryMethodName());
setRole(original.getRole());
setSource(original.getSource());
copyAttributesFrom(original);
if (original instanceof AbstractBeanDefinition) {
final AbstractBeanDefinition originalAbd = (AbstractBeanDefinition) original;
if (originalAbd.hasBeanClass()) {
setBeanClass(originalAbd.getBeanClass());
}
if (originalAbd.hasConstructorArgumentValues()) {
setConstructorArgumentValues(new ConstructorArgumentValues(original.getConstructorArgumentValues()));
}
if (originalAbd.hasPropertyValues()) {
setPropertyValues(new MutablePropertyValues(original.getPropertyValues()));
}
if (originalAbd.hasMethodOverrides()) {
setMethodOverrides(new MethodOverrides(originalAbd.getMethodOverrides()));
}
setAutowireMode(originalAbd.getAutowireMode());
setDependencyCheck(originalAbd.getDependencyCheck());
setDependsOn(originalAbd.getDependsOn());
setAutowireCandidate(originalAbd.isAutowireCandidate());
setPrimary(originalAbd.isPrimary());
copyQualifiersFrom(originalAbd);
setInstanceSupplier(originalAbd.getInstanceSupplier());
setNonPublicAccessAllowed(originalAbd.isNonPublicAccessAllowed());
setLenientConstructorResolution(originalAbd.isLenientConstructorResolution());
setInitMethodName(originalAbd.getInitMethodName());
setEnforceInitMethod(originalAbd.isEnforceInitMethod());
setDestroyMethodName(originalAbd.getDestroyMethodName());
setEnforceDestroyMethod(originalAbd.isEnforceDestroyMethod());
setSynthetic(originalAbd.isSynthetic());
setResource(originalAbd.getResource());
}
else {
setConstructorArgumentValues(new ConstructorArgumentValues(original.getConstructorArgumentValues()));
setPropertyValues(new MutablePropertyValues(original.getPropertyValues()));
setResourceDescription(original.getResourceDescription());
}
}
public void overrideFrom(BeanDefinition other) {
if (StringUtils.hasLength(other.getBeanClassName())) {
setBeanClassName(other.getBeanClassName());
}
if (StringUtils.hasLength(other.getScope())) {
setScope(other.getScope());
}
setAbstract(other.isAbstract());
setLazyInit(other.isLazyInit());
if (StringUtils.hasLength(other.getFactoryBeanName())) {
setFactoryBeanName(other.getFactoryBeanName());
}
if (StringUtils.hasLength(other.getFactoryMethodName())) {
setFactoryMethodName(other.getFactoryMethodName());
}
setRole(other.getRole());
setSource(other.getSource());
copyAttributesFrom(other);
if (other instanceof AbstractBeanDefinition) {
final AbstractBeanDefinition otherAbd = (AbstractBeanDefinition) other;
if (otherAbd.hasBeanClass()) {
setBeanClass(otherAbd.getBeanClass());
}
if (otherAbd.hasConstructorArgumentValues()) {
getConstructorArgumentValues().addArgumentValues(other.getConstructorArgumentValues());
}
if (otherAbd.hasPropertyValues()) {
getPropertyValues().addPropertyValues(other.getPropertyValues());
}
if (otherAbd.hasMethodOverrides()) {
getMethodOverrides().addOverrides(otherAbd.getMethodOverrides());
}
setAutowireMode(otherAbd.getAutowireMode());
setDependencyCheck(otherAbd.getDependencyCheck());
setDependsOn(otherAbd.getDependsOn());
setAutowireCandidate(otherAbd.isAutowireCandidate());
setPrimary(otherAbd.isPrimary());
copyQualifiersFrom(otherAbd);
setInstanceSupplier(otherAbd.getInstanceSupplier());
setNonPublicAccessAllowed(otherAbd.isNonPublicAccessAllowed());
setLenientConstructorResolution(otherAbd.isLenientConstructorResolution());
if (otherAbd.getInitMethodName() != null) {
setInitMethodName(otherAbd.getInitMethodName());
setEnforceInitMethod(otherAbd.isEnforceInitMethod());
}
if (otherAbd.getDestroyMethodName() != null) {
setDestroyMethodName(otherAbd.getDestroyMethodName());
setEnforceDestroyMethod(otherAbd.isEnforceDestroyMethod());
}
setSynthetic(otherAbd.isSynthetic());
setResource(otherAbd.getResource());
}
else {
getConstructorArgumentValues().addArgumentValues(other.getConstructorArgumentValues());
getPropertyValues().addPropertyValues(other.getPropertyValues());
setResourceDescription(other.getResourceDescription());
}
}
/**
* 将默认值应用到此 BeanDefinition
*/
public void applyDefaults(BeanDefinitionDefaults defaults) {
setLazyInit(defaults.isLazyInit());
setAutowireMode(defaults.getAutowireMode());
setDependencyCheck(defaults.getDependencyCheck());
setInitMethodName(defaults.getInitMethodName());
setEnforceInitMethod(false);
setDestroyMethodName(defaults.getDestroyMethodName());
setEnforceDestroyMethod(false);
}
@Override
public void setBeanClassName(@Nullable String beanClassName) {
beanClass = beanClassName;
}
@Override
@Nullable
public String getBeanClassName() {
final Object beanClassObject = beanClass;
if (beanClassObject instanceof Class) {
return ((Class<?>) beanClassObject).getName();
}
else {
return (String) beanClassObject;
}
}
public void setBeanClass(@Nullable Class<?> beanClass) {
this.beanClass = beanClass;
}
public Class<?> getBeanClass() throws IllegalStateException {
final Object beanClassObject = 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;
}
public boolean hasBeanClass() {
return beanClass instanceof Class;
}
@Nullable
public Class<?> resolveBeanClass(@Nullable ClassLoader classLoader) throws ClassNotFoundException {
final String className = getBeanClassName();
if (className == null) {
return null;
}
final Class<?> resolvedClass = ClassUtils.forName(className, classLoader);
beanClass = resolvedClass;
return resolvedClass;
}
@Override
public void setScope(@Nullable String scope) {
this.scope = scope;
}
@Override
@Nullable
public String getScope() {
return 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 abstractFlag;
}
@Override
public void setLazyInit(boolean lazyInit) {
this.lazyInit = lazyInit;
}
@Override
public boolean isLazyInit() {
return lazyInit;
}
/**
* @see #AUTOWIRE_NO
* @see #AUTOWIRE_BY_NAME
* @see #AUTOWIRE_BY_TYPE
* @see #AUTOWIRE_CONSTRUCTOR
* @see #AUTOWIRE_AUTODETECT
*/
public void setAutowireMode(int autowireMode) {
this.autowireMode = autowireMode;
}
public int getAutowireMode() {
return autowireMode;
}
public int getResolvedAutowireMode() {
if (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.
final Constructor<?>[] constructors = getBeanClass().getConstructors();
for (final Constructor<?> constructor : constructors) {
if (constructor.getParameterCount() == 0) {
// 如果有无参数的构造函数,则按照类型注入
return AUTOWIRE_BY_TYPE;
}
}
return AUTOWIRE_CONSTRUCTOR;
}
else {
return autowireMode;
}
}
public void setDependencyCheck(int dependencyCheck) {
this.dependencyCheck = dependencyCheck;
}
public int getDependencyCheck() {
return dependencyCheck;
}
@Override
public void setDependsOn(@Nullable String... dependsOn) {
this.dependsOn = dependsOn;
}
@Override
@Nullable
public String[] getDependsOn() {
return dependsOn;
}
@Override
public void setAutowireCandidate(boolean autowireCandidate) {
this.autowireCandidate = autowireCandidate;
}
@Override
public boolean isAutowireCandidate() {
return autowireCandidate;
}
@Override
public void setPrimary(boolean primary) {
this.primary = primary;
}
@Override
public boolean isPrimary() {
return primary;
}
public void addQualifier(AutowireCandidateQualifier qualifier) {
qualifiers.put(qualifier.getTypeName(), qualifier);
}
public boolean hasQualifier(String typeName) {
return qualifiers.keySet().contains(typeName);
}
@Nullable
public AutowireCandidateQualifier getQualifier(String typeName) {
return qualifiers.get(typeName);
}
public Set<AutowireCandidateQualifier> getQualifiers() {
return new LinkedHashSet<>(qualifiers.values());
}
public void copyQualifiersFrom(AbstractBeanDefinition source) {
Assert.notNull(source, "Source must not be null");
qualifiers.putAll(source.qualifiers);
}
public void setInstanceSupplier(@Nullable Supplier<?> instanceSupplier) {
this.instanceSupplier = instanceSupplier;
}
@Nullable
public Supplier<?> getInstanceSupplier() {
return instanceSupplier;
}
/**
* 是否允许指向此 bean 的外部化元素,访问非公共构造函数和方法。
* 注解的 private 属性不需要 setter 方法即可注入
*/
public void setNonPublicAccessAllowed(boolean nonPublicAccessAllowed) {
this.nonPublicAccessAllowed = nonPublicAccessAllowed;
}
public boolean isNonPublicAccessAllowed() {
return nonPublicAccessAllowed;
}
/**
* 是否在宽大模式下解析构造函数
*/
public void setLenientConstructorResolution(boolean lenientConstructorResolution) {
this.lenientConstructorResolution = lenientConstructorResolution;
}
public boolean isLenientConstructorResolution() {
return lenientConstructorResolution;
}
@Override
public void setFactoryBeanName(@Nullable String factoryBeanName) {
this.factoryBeanName = factoryBeanName;
}
@Override
@Nullable
public String getFactoryBeanName() {
return factoryBeanName;
}
@Override
public void setFactoryMethodName(@Nullable String factoryMethodName) {
this.factoryMethodName = factoryMethodName;
}
@Override
@Nullable
public String getFactoryMethodName() {
return factoryMethodName;
}
public void setConstructorArgumentValues(ConstructorArgumentValues constructorArgumentValues) {
this.constructorArgumentValues = constructorArgumentValues;
}
@Override
public ConstructorArgumentValues getConstructorArgumentValues() {
if (constructorArgumentValues == null) {
constructorArgumentValues = new ConstructorArgumentValues();
}
return constructorArgumentValues;
}
@Override
public boolean hasConstructorArgumentValues() {
return constructorArgumentValues != null && !constructorArgumentValues.isEmpty();
}
public void setPropertyValues(MutablePropertyValues propertyValues) {
this.propertyValues = propertyValues;
}
@Override
public MutablePropertyValues getPropertyValues() {
if (propertyValues == null) {
propertyValues = new MutablePropertyValues();
}
return propertyValues;
}
@Override
public boolean hasPropertyValues() {
return propertyValues != null && !propertyValues.isEmpty();
}
public void setMethodOverrides(MethodOverrides methodOverrides) {
this.methodOverrides = methodOverrides;
}
public MethodOverrides getMethodOverrides() {
if (methodOverrides == null) {
methodOverrides = new MethodOverrides();
}
return methodOverrides;
}
public boolean hasMethodOverrides() {
return methodOverrides != null && !methodOverrides.isEmpty();
}
@Override
public void setInitMethodName(@Nullable String initMethodName) {
this.initMethodName = initMethodName;
}
@Override
@Nullable
public String getInitMethodName() {
return initMethodName;
}
public void setEnforceInitMethod(boolean enforceInitMethod) {
this.enforceInitMethod = enforceInitMethod;
}
public boolean isEnforceInitMethod() {
return enforceInitMethod;
}
@Override
public void setDestroyMethodName(@Nullable String destroyMethodName) {
this.destroyMethodName = destroyMethodName;
}
@Override
@Nullable
public String getDestroyMethodName() {
return destroyMethodName;
}
public void setEnforceDestroyMethod(boolean enforceDestroyMethod) {
this.enforceDestroyMethod = enforceDestroyMethod;
}
public boolean isEnforceDestroyMethod() {
return enforceDestroyMethod;
}
public void setSynthetic(boolean synthetic) {
this.synthetic = synthetic;
}
public boolean isSynthetic() {
return synthetic;
}
@Override
public void setRole(int role) {
this.role = role;
}
@Override
public int getRole() {
return role;
}
@Override
public void setDescription(@Nullable String description) {
this.description = description;
}
@Override
@Nullable
public String getDescription() {
return description;
}
public void setResource(@Nullable Resource resource) {
this.resource = resource;
}
@Nullable
public Resource getResource() {
return resource;
}
public void setResourceDescription(@Nullable String resourceDescription) {
resource = resourceDescription != null ? new DescriptiveResource(resourceDescription) : null;
}
@Override
@Nullable
public String getResourceDescription() {
return resource != null ? resource.getDescription() : null;
}
public void setOriginatingBeanDefinition(BeanDefinition originatingBd) {
resource = new BeanDefinitionResource(originatingBd);
}
@Override
@Nullable
public BeanDefinition getOriginatingBeanDefinition() {
return resource instanceof BeanDefinitionResource ?
((BeanDefinitionResource) resource).getBeanDefinition() : null;
}
/**
* 验证此 BeanDefinition
*/
public void validate() throws BeanDefinitionValidationException {
if (hasMethodOverrides() && getFactoryMethodName() != null) {
throw new BeanDefinitionValidationException(
"Cannot combine static factory method with method overrides: " +
"the static factory method must create the instance");
}
if (hasBeanClass()) {
prepareMethodOverrides();
}
}
public void prepareMethodOverrides() throws BeanDefinitionValidationException {
// Check that lookup methods exists.
if (hasMethodOverrides()) {
final Set<MethodOverride> overrides = getMethodOverrides().getOverrides();
synchronized (overrides) {
for (final MethodOverride mo : overrides) {
prepareMethodOverride(mo);
}
}
}
}
protected void prepareMethodOverride(MethodOverride mo) throws BeanDefinitionValidationException {
final int count = ClassUtils.getMethodCountForName(getBeanClass(), mo.getMethodName());
if (count == 0) {
throw new BeanDefinitionValidationException(
"Invalid method override: no method with name '" + mo.getMethodName() +
"' on class [" + getBeanClassName() + "]");
}
else if (count == 1) {
// Mark override as not overloaded, to avoid the overhead of arg type checking.
mo.setOverloaded(false);
}
}
@Override
public Object clone() {
return cloneBeanDefinition();
}
/**
* 克隆此 BeanDefinition
*/
public abstract AbstractBeanDefinition cloneBeanDefinition();
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof AbstractBeanDefinition)) {
return false;
}
final AbstractBeanDefinition that = (AbstractBeanDefinition) other;
boolean rtn = ObjectUtils.nullSafeEquals(getBeanClassName(), that.getBeanClassName());
rtn = rtn &= ObjectUtils.nullSafeEquals(scope, that.scope);
rtn = rtn &= abstractFlag == that.abstractFlag;
rtn = rtn &= lazyInit == that.lazyInit;
rtn = rtn &= autowireMode == that.autowireMode;
rtn = rtn &= dependencyCheck == that.dependencyCheck;
rtn = rtn &= Arrays.equals(dependsOn, that.dependsOn);
rtn = rtn &= autowireCandidate == that.autowireCandidate;
rtn = rtn &= ObjectUtils.nullSafeEquals(qualifiers, that.qualifiers);
rtn = rtn &= primary == that.primary;
rtn = rtn &= nonPublicAccessAllowed == that.nonPublicAccessAllowed;
rtn = rtn &= lenientConstructorResolution == that.lenientConstructorResolution;
rtn = rtn &= ObjectUtils.nullSafeEquals(constructorArgumentValues, that.constructorArgumentValues);
rtn = rtn &= ObjectUtils.nullSafeEquals(propertyValues, that.propertyValues);
rtn = rtn &= ObjectUtils.nullSafeEquals(methodOverrides, that.methodOverrides);
rtn = rtn &= ObjectUtils.nullSafeEquals(factoryBeanName, that.factoryBeanName);
rtn = rtn &= ObjectUtils.nullSafeEquals(factoryMethodName, that.factoryMethodName);
rtn = rtn &= ObjectUtils.nullSafeEquals(initMethodName, that.initMethodName);
rtn = rtn &= enforceInitMethod == that.enforceInitMethod;
rtn = rtn &= ObjectUtils.nullSafeEquals(destroyMethodName, that.destroyMethodName);
rtn = rtn &= enforceDestroyMethod == that.enforceDestroyMethod;
rtn = rtn &= synthetic == that.synthetic;
rtn = rtn &= role == that.role;
return rtn && super.equals(other);
}
@Override
public int hashCode() {
int hashCode = ObjectUtils.nullSafeHashCode(getBeanClassName());
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(scope);
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(constructorArgumentValues);
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(propertyValues);
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(factoryBeanName);
hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(factoryMethodName);
hashCode = 29 * hashCode + super.hashCode();
return hashCode;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("class [");
sb.append(getBeanClassName()).append("]");
sb.append("; scope=").append(scope);
sb.append("; abstract=").append(abstractFlag);
sb.append("; lazyInit=").append(lazyInit);
sb.append("; autowireMode=").append(autowireMode);
sb.append("; dependencyCheck=").append(dependencyCheck);
sb.append("; autowireCandidate=").append(autowireCandidate);
sb.append("; primary=").append(primary);
sb.append("; factoryBeanName=").append(factoryBeanName);
sb.append("; factoryMethodName=").append(factoryMethodName);
sb.append("; initMethodName=").append(initMethodName);
sb.append("; destroyMethodName=").append(destroyMethodName);
if (resource != null) {
sb.append("; defined in ").append(resource.getDescription());
}
return sb.toString();
}
}
/**
* 合并的 BeanDefinition
*/
@SuppressWarnings("serial")
public class RootBeanDefinition extends AbstractBeanDefinition {
/**
* 持有 bean 名称、bean 别名和 BeanDefinition 的包装器
*/
@Nullable
private BeanDefinitionHolder decoratedDefinition;
/**
* 注解元素
*/
@Nullable
private AnnotatedElement qualifiedElement;
/**
* 允许缓存
*/
boolean allowCaching = true;
boolean isFactoryMethodUnique = false;
@Nullable
volatile ResolvableType targetType;
/** 此 BeanDefinition 关联的 Class 类型 */
@Nullable
volatile Class<?> resolvedTargetType;
/** 泛型工厂方法的返回类型 */
@Nullable
volatile ResolvableType factoryMethodReturnType;
/** 缓存用于内省的惟一工厂方法 */
@Nullable
volatile Method factoryMethodToIntrospect;
/** 以下 4 个构造函数的锁 */
final Object constructorArgumentLock = new Object();
/** 已解析的构造函数或工厂方法 */
@Nullable
Executable resolvedConstructorOrFactoryMethod;
/** 构造函数参数是否已解析 */
boolean constructorArgumentsResolved = false;
/** 已解析的构造函数参数 */
@Nullable
Object[] resolvedConstructorArguments;
/** 部分准备的构造函数参数 */
@Nullable
Object[] preparedConstructorArguments;
/** Common lock for the two post-processing fields below. */
final Object postProcessingLock = new Object();
/** 是否已应用了 MergedBeanDefinitionPostProcessor */
boolean postProcessed = false;
/** before-instantiation post-processor 已启动 */
@Nullable
volatile Boolean beforeInstantiationResolved;
/**
* 外部管理的配置成员
*/
@Nullable
private Set<Member> externallyManagedConfigMembers;
/**
* 外部管理的初始化方法
*/
@Nullable
private Set<String> externallyManagedInitMethods;
/**
* 外部管理的销毁方法
*/
@Nullable
private Set<String> externallyManagedDestroyMethods;
public RootBeanDefinition() {
super();
}
public RootBeanDefinition(@Nullable Class<?> beanClass) {
super();
setBeanClass(beanClass);
}
public <T> RootBeanDefinition(@Nullable Class<T> beanClass, @Nullable Supplier<T> instanceSupplier) {
super();
setBeanClass(beanClass);
setInstanceSupplier(instanceSupplier);
}
public <T> RootBeanDefinition(@Nullable Class<T> beanClass, String scope, @Nullable Supplier<T> instanceSupplier) {
super();
setBeanClass(beanClass);
setScope(scope);
setInstanceSupplier(instanceSupplier);
}
*/
public RootBeanDefinition(@Nullable Class<?> beanClass, int autowireMode, boolean dependencyCheck) {
super();
setBeanClass(beanClass);
setAutowireMode(autowireMode);
if (dependencyCheck && getResolvedAutowireMode() != AUTOWIRE_CONSTRUCTOR) {
setDependencyCheck(DEPENDENCY_CHECK_OBJECTS);
}
}
public RootBeanDefinition(@Nullable Class<?> beanClass, @Nullable ConstructorArgumentValues cargs,
@Nullable 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);
}
public RootBeanDefinition(RootBeanDefinition original) {
super(original);
decoratedDefinition = original.decoratedDefinition;
qualifiedElement = original.qualifiedElement;
allowCaching = original.allowCaching;
isFactoryMethodUnique = original.isFactoryMethodUnique;
targetType = original.targetType;
}
RootBeanDefinition(BeanDefinition original) {
super(original);
}
@Override
public String getParentName() {
return null;
}
@Override
public void setParentName(@Nullable String parentName) {
if (parentName != null) {
throw new IllegalArgumentException("Root bean cannot be changed into a child bean with parent reference");
}
}
public void setDecoratedDefinition(@Nullable BeanDefinitionHolder decoratedDefinition) {
this.decoratedDefinition = decoratedDefinition;
}
@Nullable
public BeanDefinitionHolder getDecoratedDefinition() {
return decoratedDefinition;
}
public void setQualifiedElement(@Nullable AnnotatedElement qualifiedElement) {
this.qualifiedElement = qualifiedElement;
}
@Nullable
public AnnotatedElement getQualifiedElement() {
return qualifiedElement;
}
public void setTargetType(ResolvableType targetType) {
this.targetType = targetType;
}
public void setTargetType(@Nullable Class<?> targetType) {
this.targetType = targetType != null ? ResolvableType.forClass(targetType) : null;
}
@Nullable
public Class<?> getTargetType() {
if (resolvedTargetType != null) {
return resolvedTargetType;
}
final ResolvableType targetType = this.targetType;
return targetType != null ? targetType.resolve() : null;
}
public ResolvableType getResolvableType() {
final ResolvableType targetType = this.targetType;
return targetType != null ? targetType : ResolvableType.forClass(getBeanClass());
}
@Nullable
public Constructor<?>[] getPreferredConstructors() {
return null;
}
public void setUniqueFactoryMethodName(String name) {
Assert.hasText(name, "Factory method name must not be empty");
setFactoryMethodName(name);
isFactoryMethodUnique = true;
}
public boolean isFactoryMethod(Method candidate) {
return candidate.getName().equals(getFactoryMethodName());
}
@Nullable
public Method getResolvedFactoryMethod() {
return factoryMethodToIntrospect;
}
public void registerExternallyManagedConfigMember(Member configMember) {
synchronized (postProcessingLock) {
if (externallyManagedConfigMembers == null) {
externallyManagedConfigMembers = new HashSet<>(1);
}
externallyManagedConfigMembers.add(configMember);
}
}
public boolean isExternallyManagedConfigMember(Member configMember) {
synchronized (postProcessingLock) {
return externallyManagedConfigMembers != null &&
externallyManagedConfigMembers.contains(configMember);
}
}
/**
* @PostConstruct
*/
public void registerExternallyManagedInitMethod(String initMethod) {
synchronized (postProcessingLock) {
if (externallyManagedInitMethods == null) {
externallyManagedInitMethods = new HashSet<>(1);
}
externallyManagedInitMethods.add(initMethod);
}
}
public boolean isExternallyManagedInitMethod(String initMethod) {
synchronized (postProcessingLock) {
return externallyManagedInitMethods != null &&
externallyManagedInitMethods.contains(initMethod);
}
}
/**
* @PreDestroy
*/
public void registerExternallyManagedDestroyMethod(String destroyMethod) {
synchronized (postProcessingLock) {
if (externallyManagedDestroyMethods == null) {
externallyManagedDestroyMethods = new HashSet<>(1);
}
externallyManagedDestroyMethods.add(destroyMethod);
}
}
public boolean isExternallyManagedDestroyMethod(String destroyMethod) {
synchronized (postProcessingLock) {
return externallyManagedDestroyMethods != null &&
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();
}
}
/**
* 标准 bean 定义的 GenericBeanDefinition,主要用于 XML 配置中的 bean
*/
@SuppressWarnings("serial")
public class GenericBeanDefinition extends AbstractBeanDefinition {
@Nullable
private String parentName;
public GenericBeanDefinition() {
super();
}
public GenericBeanDefinition(BeanDefinition original) {
super(original);
}
@Override
public void setParentName(@Nullable String parentName) {
this.parentName = parentName;
}
@Override
@Nullable
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();
}
}
- ScannedGenericBeanDefinition
/**
* 基于包扫描发现,通过注解加入到容器中的 BeanDefinition
*/
@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
@Nullable
public MethodMetadata getFactoryMethodMetadata() {
return null;
}
}
- AnnotatedGenericBeanDefinition
@SuppressWarnings("serial")
public class AnnotatedGenericBeanDefinition extends GenericBeanDefinition implements AnnotatedBeanDefinition {
/**
* 类注解元数据
*/
private final AnnotationMetadata metadata;
/**
* 方法元数据
*/
@Nullable
private MethodMetadata factoryMethodMetadata;
public AnnotatedGenericBeanDefinition(Class<?> beanClass) {
setBeanClass(beanClass);
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 metadata;
}
@Override
@Nullable
public final MethodMetadata getFactoryMethodMetadata() {
return factoryMethodMetadata;
}
}
- ConfigurationClassBeanDefinition
ConfigurationClassBeanDefinitionReader#
/**
* 配置类 BeanDefinition、包括通过 @Bean 注解创建的 BeanDefinition
*/
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);
}
}