美文网首页
Spring的属性编辑器PropertyEditor

Spring的属性编辑器PropertyEditor

作者: yang2yang | 来源:发表于2016-12-18 18:52 被阅读145次

尝试解析上一篇blog的一个小例子,加深理解。

public class PropertyTest {

    public static void main(String[] args) {
        TestModel tm = new TestModel();
        BeanWrapper bw = new BeanWrapperImpl(tm);

        bw.setPropertyValue("good","on");

        System.out.println(tm);

    }
}
Paste_Image.png

走完了nestedPa.setPropertyValue(tokens, new PropertyValue(propertyName, value));,从上图中可以看到rootObjectgood属性被赋值了true。然后尝试进入nestedPa.setPropertyValue(tokens, new PropertyValue(propertyName, value));,可以发现下面这张图片。

Paste_Image.png

从上图中可以看到tm对象的引用在this.wrappedObject里面,而将on转化过的true在变量valueToApply中。然后在进入到函数convertForProperty()中。最后辗转找到下面这个函数。

Paste_Image.png

从上图中可以发现传递过来的参数是

  • propertyName:"good",是要设置值的属性名字。
  • oldValue:null,是指原来这个对象中的good属性值是null。
  • newValue:"on",是指现在新的值需要设置为on
  • requiredType:"boolean",是指现在这个叫做good的属性值的类型是boolean
  • typeDescriptor:"boolean",是指
Paste_Image.png
在函数convertIfNecessary里面发现最后返回的参数是convertedValue,所以在上图这里的时候convertedValue还是on,但是这个函数过了之后就是true了。所以这个函数里面就有类型转换的代码了。 Paste_Image.png

从上图中可以看到当convertedValueString类型的时候,正好onString类型的,会调用doConvertedTextValue函数。虽然这里convertedValue是个Object的,但是instanceof还是能够判断出来这个Object里面的变量是值是String类型的。

Paste_Image.png

外面那么多判断,终于进入了属性编辑器PropertyEditor的东西了,注意这里PropertyEditor的实例是CustomBooleanEditor,这里有个语句是editor.setAsText(newTextValue),所以查看CustomBooleanEditoreditor.setAsText(newTextValue)

Paste_Image.png Paste_Image.png

从上面两张图中可以发现当传入的字符串是on的时候,会设置内部的value的值为true。最后就是返回了,一层一层的返回。

Paste_Image.png

上图进入之后发现通过反射调用,将值设置进入到wrappedObject中。

Paste_Image.png Paste_Image.png

从上面的两张图中可以发现首先在setValue()函数中,得到需要调用的函数的名字是writeMethod这个是个java.lang.reflect.Method的,然后就可以正常调用反射的知识,将值设置进入变量中。

参考

学习Spring必学的Java基础知识(3)----PropertyEditor

相关文章

网友评论

      本文标题:Spring的属性编辑器PropertyEditor

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