Spring之Ⅰ:BeanDefinition
BeanDefinition定义
BeanDefinition描述一个bean实例,这个bean实例包含了属性值,构造函数的参数值,以及由具体实现提供额进一步信息。
这是仅仅是一个最轻量的接口:主要目的是允许像 PropertyPlaceholderConfigurer 这样的 BeanFactoryPostProcessor来内省和改变
属性值以及其他bean的元数据
BeanDefinition相关的类图
从上往下说明:
1、AttributeAccessor接口:定义了向任意对象附加和访问元数据的通用契约的接口。
//元数据操作接口 public interface AttributeAccessor { //设置元数据 //最好使用全限定类名作为参数,否则容易被其他元数据覆盖 void setAttribute(String name, Object value); //获取元数据 Object getAttribute(String name); //删除元数据 Object removeAttribute(String name); //是否含有元数据 boolean hasAttribute(String name); //获取元数据的name数组 String[] attributeNames(); }
AttributeAccessorSupport
抽象类,AttributeAccessor支持类,主要针对属性CRUD操作。
主要方法、属性如下:
@SuppressWarnings("serial") public abstract class AttributeAccessorSupport implements AttributeAccessor, Serializable { /** Map with String keys and Object values */ private final Map<String, Object> attributes = new LinkedHashMap<String, Object>(0); @Override public void setAttribute(String name, Object value) { Assert.notNull(name, "Name must not be null"); if (value != null) { this.attributes.put(name, value); } else { removeAttribute(name); } } @Override public Object getAttribute(String name) { Assert.notNull(name, "Name must not be null"); return this.attributes.get(name); } @Override public Object removeAttribute(String name) { Assert.notNull(name, "Name must not be null"); return this.attributes.remove(name); } @Override public boolean hasAttribute(String name) { Assert.notNull(name, "Name must not be null"); return this.attributes.containsKey(name); } @Override public String[] attributeNames() { return this.attributes.keySet().toArray(new String[this.attributes.size()]); } /** * Copy the attributes from the supplied AttributeAccessor to this accessor. * @param source the AttributeAccessor to copy from */ protected void copyAttributesFrom(AttributeAccessor source) { Assert.notNull(source, "Source must not be null"); String[] attributeNames = source.attributeNames(); for (String attributeName : attributeNames) { setAttribute(attributeName, source.getAttribute(attributeName)); } }
2、BeanMetadataElement接口:用于传输配置源对象(对象的确切类型将取决于所使用的配置机制),在配置源对象中可获取 bean 元数据元素。主要方法:
public interface BeanMetadataElement { Object getSource(); }
BeanMetadataAttributeAccessor:
为了追踪对象定义源,实现了BeanMetadataElement接口的getResource()方法也提供了 AttributeAccessorSupport 针对属性的增删改查。主要方法如下:
@SuppressWarnings("serial") public class BeanMetadataAttributeAccessor extends AttributeAccessorSupport implements BeanMetadataElement { private Object source; /** * Set the configuration source {@code Object} for this metadata element. * <p>The exact type of the object will depend on the configuration mechanism used. */ public void setSource(Object source) { this.source = source; } @Override public Object getSource() { return this.source; } /** * Add the given BeanMetadataAttribute to this accessor's set of attributes. * @param attribute the BeanMetadataAttribute object to register */ public void addMetadataAttribute(BeanMetadataAttribute attribute) { super.setAttribute(attribute.getName(), attribute); } /** * Look up the given BeanMetadataAttribute in this accessor's set of attributes. * @param name the name of the attribute * @return the corresponding BeanMetadataAttribute object, * or {@code null} if no such attribute defined */ public BeanMetadataAttribute getMetadataAttribute(String name) { return (BeanMetadataAttribute) super.getAttribute(name); } @Override public void setAttribute(String name, Object value) { super.setAttribute(name, new BeanMetadataAttribute(name, value)); } @Override public Object getAttribute(String name) { BeanMetadataAttribute attribute = (BeanMetadataAttribute) super.getAttribute(name); return (attribute != null ? attribute.getValue() : null); } @Override public Object removeAttribute(String name) { BeanMetadataAttribute attribute = (BeanMetadataAttribute) super.removeAttribute(name); return (attribute != null ? attribute.getValue() : null); } }
3、BeanDefinition接口
配置文件元素标签在容器中内部表示形式,一个BeanDefinition描述了一个bean的实例,包括属性值,构造方法参数值和继承自它的类的更多信息。
BeanDefinition仅仅是一个最简单的接口,主要功能是允许BeanFactoryPostProcessor,比如实现类 PropertyPlaceHolderConfigure 能够检索并修改属性值和别的bean的元数据。
//用于描述一个具体bean实例 public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement { //scope值,单例 String SCOPE_SINGLETON = ConfigurableBeanFactory.SCOPE_SINGLETON; //scope值,非单例 String SCOPE_PROTOTYPE = ConfigurableBeanFactory.SCOPE_PROTOTYPE; //Bean角色: //用户 int ROLE_APPLICATION = 0; //某些复杂的配置 int ROLE_SUPPORT = 1; //完全内部使用 int ROLE_INFRASTRUCTURE = 2; //返回此bean定义的父bean定义的名称,如果有的话 <bean parent=""> String getParentName(); void setParentName(String parentName); //获取bean对象className <bean class=""> String getBeanClassName(); void setBeanClassName(String beanClassName); //定义创建该Bean对象的工厂l类 <bean factory-bean=""> String getFactoryBeanName(); void setFactoryBeanName(String factoryBeanName); //定义创建该Bean对象的工厂方法 <bean factory-method=""> String getFactoryMethodName(); void setFactoryMethodName(String factoryMethodName); //<bean scope="singleton/prototype"> String getScope(); void setScope(String scope); //懒加载 <bean lazy-init="true/false"> boolean isLazyInit(); void setLazyInit(boolean lazyInit); //依赖对象 <bean depends-on=""> String[] getDependsOn(); void setDependsOn(String[] dependsOn); //是否为被自动装配 <bean autowire-candidate="true/false"> boolean isAutowireCandidate(); void setAutowireCandidate(boolean autowireCandidate); //是否为主候选bean 使用注解:@Primary boolean isPrimary(); void setPrimary(boolean primary); //返回此bean的构造函数参数值。 ConstructorArgumentValues getConstructorArgumentValues(); //获取普通属性集合 MutablePropertyValues getPropertyValues(); //是否为单例 boolean isSingleton(); //是否为原型 boolean isPrototype(); //是否为抽象类 boolean isAbstract(); //获取这个bean的应用 int getRole(); //返回对bean定义的可读描述。 String getDescription(); //返回该bean定义来自的资源的描述(用于在出现错误时显示上下文) String getResourceDescription(); BeanDefinition getOriginatingBeanDefinition(); }
AbstractBeanDefinition抽象类
配置文件元素标签在容器中内部表示形式,一个BeanDefinition描述了一个bean的实例,包括属性值,构造方法参数值和继承自它的类的更多信息。
public abstract class AbstractBeanDefinition extends BeanMetadataAttributeAccessor implements BeanDefinition, Cloneable { }
主要方法:
@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() }
AnnotatedBeanDefinition接口:
public interface AnnotatedBeanDefinition extends BeanDefinition { //获取该bean definition的注解元数据。 AnnotationMetadata getMetadata(); //获取该bean definition的注解元数据。 MethodMetadata getFactoryMethodMetadata(); }
BeanDefinition的实现类:
ChildBeanDefinition, GenericBeanDefinition, RootBeanDefinition
ChildBeanDefinition
ChildBeanDefinition是一种bean definition,它可以继承它父类的设置,即ChildBeanDefinition对RootBeanDefinition有一定的依赖关系。
ChildBeanDefinition从父类继承构造参数值,属性值并可以重写父类的方法,同时也可以增加新的属性或者方法。(类同于java类的继承关系)。若指定初始化方法,销毁方法或者静态工厂方法,ChildBeanDefinition将重写相应父类的设置。depends on,autowire mode,dependency check,sigleton,lazy init 一般由子类自行设定。
GenericBeanDefinition
注意:从spring 2.5 开始,提供了一个更好的注册bean definition类GenericBeanDefinition,它支持动态定义父依赖,方法是GenericBeanDefinition.setParentName(java.lang.String),GenericBeanDefinition可以有效的替代ChildBeanDefinition的绝大分部使用场合。
GenericBeanDefinition是一站式的标准bean definition,除了具有指定类、可选的构造参数值和属性参数这些其它bean definition一样的特性外,它还具有通过parenetName属性来灵活设置parent bean definition。
通常, GenericBeanDefinition用来注册用户可见的bean definition(可见的bean definition意味着可以在该类bean definition上定义post-processor来对bean进行操作,甚至为配置parent name做扩展准备)。RootBeanDefinition / ChildBeanDefinition用来预定义具有parent/child关系的bean definition。
RootBeanDefinition
一个RootBeanDefinition定义表明它是一个可合并的bean definition:即在spring beanFactory运行期间,可以返回一个特定的bean。RootBeanDefinition可以作为一个重要的通用的bean definition 视图。
RootBeanDefinition用来在配置阶段进行注册bean definition。然后,从spring 2.5后,编写注册bean definition有了更好的的方法:GenericBeanDefinition。GenericBeanDefinition支持动态定义父类依赖,而非硬编码作为root bean definition。