美文网首页Spring
spring之IOC容器BeanDefinition(bean定

spring之IOC容器BeanDefinition(bean定

作者: Mr_1214 | 来源:发表于2018-11-30 19:36 被阅读15次

    描述

    BeanDefintion定义了Bean在IoC容器内的基本数据结构,BeanDefinition描述了一个bean的实例,包括属性值,构造方法参数值和继承自它的类的更多信息,在Spring容器启动的过程中,会将Bean解析成Spring内部的BeanDefinition结构存储

    BeanDefinition主要功能是允许BeanFactoryPostProcessor (例如:PropertyPlaceHolderConfigure)等检索并修改属性值和别的bean的元数据

    BeanDefinition 是一个接口,继承了AttributeAccessor和BeanMetadataElement。实现类有:

    • AbstractBeanDefinition:抽象类,但是提供了BeanDefinition接口的全部实现。基础类,子类继承于此类
    • RootBeanDefinition:表示父级bean
    • ChildBeanDefinition:表示子级bean
    • GenericBeanDefinition:一般的BeanDefinition实现
    • AnnotatedBeanDefinition: 注解类型的BeanDefinition

    类体系图

    imageimage

    核心类

    AttributeAccessor

    AttributeAccessor接口定义了属性(key-value)修改或者获取。AttributeAccessor为 BeanDefinition的父接口,使BeanDefinition具有处理属性的功能

    public interface AttributeAccessor {
    
        /**
         * 设置属性信息
         */
        void setAttribute(String name, @Nullable Object value);
    
        /**
         * 根据名称获取属性值 
         */
        @Nullable
        Object getAttribute(String name);
    
        /**
         * 根据名称移除属性
         */
        @Nullable
        Object removeAttribute(String name);
    
        /**
         * 判断是否函数此名称的属性
         */
        boolean hasAttribute(String name);
    
        /**
         * 返回所有属性
         * Return the names of all attributes.
         */
        String[] attributeNames();
    
    }
    
    BeanMetadataElement
    public interface BeanMetadataElement {
    
        /**
         * 获取可配置的源对象
         * Return the configuration source {@code Object} for this metadata element
         * (may be {@code null}).
         */
        @Nullable
        Object getSource();
    
    }
    

    BeanMetadataElement接口提供了一个getResource()方法,用来传输一个可配置的源对象,BeanDefinition继承了BeanMetadataElement,说明BeanDefinition同样可以持有Bean元数据元素

    BeanDefinition
    public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement {
    
        /**
         * 作用域:单例
         */
        String SCOPE_SINGLETON = ConfigurableBeanFactory.SCOPE_SINGLETON;
    
        /**
         * 作用域:new
         */
        String SCOPE_PROTOTYPE = ConfigurableBeanFactory.SCOPE_PROTOTYPE;
    
    
        /**
         * 角色:APPLICATION
         */
        int ROLE_APPLICATION = 0;
    
        /**
         */
        int ROLE_SUPPORT = 1;
    
        /**
         */
        int ROLE_INFRASTRUCTURE = 2;
    
    
        // Modifiable attributes
    
        /**
         * 设置bean定义的父定义名称
         */
        void setParentName(@Nullable String parentName);
    
        /**
         * 返回bean定义的父定义名称
         */
        @Nullable
        String getParentName();
    
        /**
         * 设置bean定义描述的bean的class类名
         */
        void setBeanClassName(@Nullable String beanClassName);
    
        /**
         * 返回bean定义描述的bean的class类名
         */
        @Nullable
        String getBeanClassName();
    
        /**
         * 设置bean的作用域
         */
        void setScope(@Nullable String scope);
    
        /**
         * 返回bean的作用域
         */
        @Nullable
        String getScope();
    
        /**
         * 设置延迟加载标识
         */
        void setLazyInit(boolean lazyInit);
    
        /**
         * 返回延迟加载标识
         */
        boolean isLazyInit();
    
        /**
         * 设置bean依赖于初始化的bean的名称。
         * bean工厂将保证这些bean首先被初始化。
         */
        void setDependsOn(@Nullable String... dependsOn);
    
        /**
         * 返回依赖于初始化的bean的名称
         */
        @Nullable
        String[] getDependsOn();
    
        /**
         * 设置bean是否自动搜索相同其它bean标识
         */
        void setAutowireCandidate(boolean autowireCandidate);
    
        /**
         * 返回bean是否自动搜索相同其它bean标识
         */
        boolean isAutowireCandidate();
    
        /**
         * 设置当前bean是否为primary
         */
        void setPrimary(boolean primary);
    
        /**
         */
        boolean isPrimary();
    
        /**
         * 设置要使用的FactoryBean 的名称
         */
        void setFactoryBeanName(@Nullable String factoryBeanName);
    
        /**
         * 返回要使用的FactoryBean 的名称
         */
        @Nullable
        String getFactoryBeanName();
    
        /**
         * 设置要使用的FactoryMethod 名称
         */
        void setFactoryMethodName(@Nullable String factoryMethodName);
    
        /**
         * Return a factory method, if any.
         */
        @Nullable
        String getFactoryMethodName();
    
        /**
         * 返回bean的构造参数值
         */
        ConstructorArgumentValues getConstructorArgumentValues();
    
        /**
         * 判断是否存在构造参数值
         * @since 5.0.2
         */
        default boolean hasConstructorArgumentValues() {
            return !getConstructorArgumentValues().isEmpty();
        }
    
        /**
         * 返回bean的属性值
         */
        MutablePropertyValues getPropertyValues();
    
        /**
         * 判断bean是否存在属性值
         * @since 5.0.2
         */
        default boolean hasPropertyValues() {
            return !getPropertyValues().isEmpty();
        }
    
    
        // Read-only attributes
    
        /**
         * 判断bean是否为单例模式
         */
        boolean isSingleton();
    
        /**
    
         */
        boolean isPrototype();
    
        /**
         * 返回bean是否为抽象类
         */
        boolean isAbstract();
    
        /**
         * 返回角色
         */
        int getRole();
    
        /**
         * 返回bean的描述信息
         */
        @Nullable
        String getDescription();
    
        /**
         * 返回bean定义的资源的描述信息
         */
        @Nullable
        String getResourceDescription();
    
        /**
    
         */
        @Nullable
        BeanDefinition getOriginatingBeanDefinition();
    
    }
    

    BeanDefinition 包含了对bean的所有描述信息,是IOC保存bean的基本数据结构,同时对外提供了获取,修改bean描述的各种方法。

    AbstractBeanDefinition
    public abstract class AbstractBeanDefinition extends BeanMetadataAttributeAccessor
            implements BeanDefinition, Cloneable {
    
    
        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;
    
        /**
         * Constant that indicates autowiring a constructor.
         * @see #setAutowireMode
         */
        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;
    
        //检查简单类型属性以及集合类型属性
        public static final int DEPENDENCY_CHECK_SIMPLE = 2;
    
       //全部检查
        public static final int DEPENDENCY_CHECK_ALL = 3;
    
    
        public static final String INFER_METHOD = "(inferred)";
    
    //表示这个Bean的类,可能是字符串,比如"com.insaneXs.TestA",也可能是class对象
        @Nullable
        private volatile Object beanClass;
      //表示这个bean的范围
        @Nullable
        private String scope = SCOPE_DEFAULT;
    //是否是抽象的,在定义bean的时候,由abstract属性设置,抽象的BeanDefition在getBean时会抛出异常
        private boolean abstractFlag = false;
     //是否延迟加载
        private boolean lazyInit = false;
    
        private int autowireMode = AUTOWIRE_NO;
    
    
        private int dependencyCheck = DEPENDENCY_CHECK_NONE;
     //依赖关系,在定义bean的时候,由depend-on属性设置,被依赖的bean在该bean之前被容器初始化
        @Nullable
        private String[] dependsOn;
    
        private boolean autowireCandidate = true;
    
        private boolean primary = false;
    
        private final Map<String, AutowireCandidateQualifier> qualifiers = new LinkedHashMap<>(0);
    
        @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;
    
    
        /**
         * Create a new AbstractBeanDefinition with default settings.
         */
        protected AbstractBeanDefinition() {
            this(null, null);
        }
    
        /**
         * Create a new AbstractBeanDefinition with the given
         * constructor argument values and property values.
         */
        protected AbstractBeanDefinition(@Nullable ConstructorArgumentValues cargs, @Nullable MutablePropertyValues pvs) {
            this.constructorArgumentValues = cargs;
            this.propertyValues = pvs;
        }
    
        /**
         * Create a new AbstractBeanDefinition as a deep copy of the given
         * bean definition.
         * @param original the original bean definition to copy from
         */
        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) {
                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());
            }
        }
    
    
        /**
         * Override settings in this bean definition (presumably a copied parent
         * from a parent-child inheritance relationship) from the given bean
         * definition (presumably the child).
         * <ul>
         * <li>Will override beanClass if specified in the given bean definition.
         * <li>Will always take {@code abstract}, {@code scope},
         * {@code lazyInit}, {@code autowireMode}, {@code dependencyCheck},
         * and {@code dependsOn} from the given bean definition.
         * <li>Will add {@code constructorArgumentValues}, {@code propertyValues},
         * {@code methodOverrides} from the given bean definition to existing ones.
         * <li>Will override {@code factoryBeanName}, {@code factoryMethodName},
         * {@code initMethodName}, and {@code destroyMethodName} if specified
         * in the given bean definition.
         * </ul>
         */
        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) {
                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());
            }
        }
    }
    

    AbstractBeanDefinition 实现BeanDefinition的所有方法,是BeanDefinition所有子类的基类。

    AnnotatedBeanDefinition
    public interface AnnotatedBeanDefinition extends BeanDefinition {
    
        /**
         * 获取注解元数据
         * Obtain the annotation metadata (as well as basic class metadata)
         * for this bean definition's bean class.
         * @return the annotation metadata object (never {@code null})
         */
        AnnotationMetadata getMetadata();
    
        /**
         * 获取工厂方法元数据
         * Obtain metadata for this bean definition's factory method, if any.
         * @return the factory method metadata, or {@code null} if none
         * @since 4.1.1
         */
        @Nullable
        MethodMetadata getFactoryMethodMetadata();
    
    }
    

    AnnotatedBeanDefinition 接口扩展了BeanDefinition 添加新的功能:获取bean的注解元数据以及工厂方法的元数据


    BeanDefinition 包装了需要让ioc容器管理的bean对象的数据信息: 依赖关系,创建方式,加载方式等。通常一个项目启动时,IOC容器启动,扫描路径,根据配置将需要容器管理的bean信息装配成BeanDefinition对象,在getBean时通过反射将BeanDefinition对象中的beanClass创建,初始化赋值(依赖注入)等操作,通过这种方式ioc容器控制bean的创建,初始化,销毁。

    相关文章

      网友评论

        本文标题:spring之IOC容器BeanDefinition(bean定

        本文链接:https://www.haomeiwen.com/subject/rdhkcqtx.html