属性编辑器PropertyEditor的扩展

spring-beans包扩展的Java的PropertyEditor,使得开发者能够轻易的调用扩展类进行对象与string类型的转换,不仅如此,spring还增加了PropertyEditorRegistry接口及其实现类,这样便能轻易地获取到对应类型的PropertyEditor

在《spring-beans概述》中,展示了spring-beans的项目结构,其中有一个包propertyeditors以及root interface PropertyEditorRegistry,这部分就是spring-beans对Java的PropertyEditor所做的扩展。

PropertyEditor

这是 java.beans中一个接口,其设计的意图是图形化编程上,方便对象与String之间的转换工作,而spring将其扩展,方便各种对象与String之间的转换工作。其部分类图如下图所示:

属性编辑器PropertyEditor的扩展_第1张图片
PropertyEditor继承树

扩展实现类PropertyEditorSupport将重心放在对象转换上,因此只要继承PropertyEditorSupport,通过重写setAsText()getAsText()以及构造方法即可实现扩展。

属性编辑器PropertyEditor的扩展_第2张图片
spring-beans所扩展的PropertyEditor
CustomDateEditor的实现

说再多都不如举一个例子来的有效。Date和String的转换应该是非常常见的,一般情况下,项目中应用的话是将其封装为一个Util工具类,然后实现互相转换的方法。我们来看下spring里是如何做对象和String相互转换的。

  • 构造函数
    通过构造函数传参,实例化出个性定制化的util对象
    public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty) {
        this.dateFormat = dateFormat;    //时间格式转换器
        this.allowEmpty = allowEmpty;    //设置是否允许时间为空
        this.exactDateLength = -1;       //设置精确对象长度,-1为不限制
    }

    public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty, int exactDateLength) {
        this.dateFormat = dateFormat;
        this.allowEmpty = allowEmpty;
        this.exactDateLength = exactDateLength;
    }
  • 重写setAsText()
    实现通过将string转换为Date对象;
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (this.allowEmpty && !StringUtils.hasText(text)) {
            // Treat empty String as null value.
            setValue(null);
        }
        else if (text != null && this.exactDateLength >= 0 && text.length() != this.exactDateLength) {
            throw new IllegalArgumentException(
                    "Could not parse date: it is not exactly" + this.exactDateLength + "characters long");
        }
        else {
            try {
                setValue(this.dateFormat.parse(text));
            }
            catch (ParseException ex) {
                throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
            }
        }
    }
  • 重写getAsText()
    获取string对象,将内置的value(即Date对象转换为String);
    @Override
    public String getAsText() {
        Date value = (Date) getValue();
        return (value != null ? this.dateFormat.format(value) : "");
    }
  • 应用
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
    CustomDateEditor editor = new CustomDateEditor(dateFormat, true);

    editor.setAsText("2017-06-24 00-00-00");
    Date date = (Date)editor.getValue();   //获取到字符串对应的date对象

    editor.setValue(new Date());
    String dateStr = editor.getAsText();    //获取到对应的字符串对象
设计意图

获取会让人觉得spring对于一个对象转换工具都如此大费周章地进行抽象封装,有点没有必要;但是想想spring的理念就不难理解了,将对象实例化,并且使用Ioc容器管理起来,对于后续扩展是有很大的好处的(拭目以待)。

小结

本文对PropertyEditor进行分析以及Beans组件对PropertyEditor进行扩展,总的说来,spring实现了一系列的对象与String相互转换的工具类。

属性编辑器PropertyEditor的扩展_第3张图片
spring-beans

你可能感兴趣的:(属性编辑器PropertyEditor的扩展)