springIoc-BeanWrapper

对于spring我们可能需要配置大量的javaBean属性,我们需要一个对对象属性进行操作的一个对象,这个对象就是BeanWrapper接口.

1.既然我们是想对工厂管理所有的bean进行属性配置,因此我们需要一个对对象属性的的访问器.
2.因为配置文件等大部分传递过来的数据都是String类型,我们很可能需要对其进行转换,能够重用
spring-core中的Conversion ,同时还的支持用户熟悉的PropertyEditor编辑器
3.因为有大量的常用Convertor PropertyEditor,我们可以将其缓存起来,这样我们不必要每次都创建
这个三方面的考虑就产生了PropertyAccessor TypeConvert PropertyEditorRegistry三个接口

PropertyAccessor(属性存取器)

定义了对javaBean属性进行访问和操作的接口
1.查看指定属性是否存在读和写的方法.(方便调用方法直接赋值)
isWritableProperty(String propertyName) isReadableProperty getPropertyTypeDescriptor
2.查看属性的类型是什么.(方便需要将传递管理的对象转换为指定类型)
Class<'?> getPropertyType(String propertyName) throws BeansException;
3.自己定义的设置对象属性的方法.
void setPropertyValue(String propertyName, Object value) throws BeansException;
void setPropertyValue(PropertyValue pv) throws BeansException;
设置对象属性的方法,修改属性的统一入口.

TypeConverter:类型转换器

把给定的值转换为指定类型
T convertIfNecessary(Object value, Class requiredType) throws TypeMismatchException;
T convertIfNecessary(Object value, Class requiredType, MethodParameter methodParam)
throws TypeMismatchException;
T convertIfNecessary(Object value, Class requiredType, Field field)
throws TypeMismatchException;
之所以会有下面两个接口,是为了可以使用上下文参数(注解)
这个类型转换器屏蔽了使用PropertyEditor 和 Conversion 方法直接的不同

PropertyEditorRegistry:PropertyEditor注册器

void registerCustomEditor(Class<’?’> requiredType, PropertyEditor propertyEditor);
void registerCustomEditor(Class<’?’> requiredType, String propertyPath, PropertyEditor propertyEditor);
根据属性名称 属性类型注册属性编辑器
PropertyEditor findCustomEditor(Class<’?’> requiredType, String propertyPath);
通过给定的属性和要求类型,查找对应的属性编辑器.

spring最终实现类为BeanWrapperImpl,实现了上述的几个接口,可以对bean进行属性赋值.
如果给定的类型不符合bean的属性类型,可以通过PropertyEditor 或者Conversion进行转换.

Created with Raphaël 2.1.0BeanWrapperImplBeanWrapperImplTypeConverterDelegateTypeConverterDelegate是否为最后一个属性,foo.age查找Conversion propertyEditor进行转换返回转换的值调用setterMethod.invoke()赋值
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章