zoukankan      html  css  js  c++  java
  • 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;
      }
    }
    
      注:文章中难免有不足之处,欢迎评论、互动、指正。

    作者: i-nine
    原创不易,本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    JS中数组Array的用法{转载}
    XML运用于编程
    Net下Attribute的特性简单入门(转)
    JS比较好用的一些方法搜集
    再也不用为找loading图标而发愁(转)
    jQuery AJAX实现调用页面后台方法
    ajax 错误: invalid label
    treeview TreeNodeCollection 转化为 TreeNode[]
    怎么页面初始化时执行js方法
    asp 前台js获取后台的值
  • 原文地址:https://www.cnblogs.com/ninth/p/6404317.html
Copyright © 2011-2022 走看看