美文网首页
spring笔记-PropertyEditor

spring笔记-PropertyEditor

作者: 兴浩 | 来源:发表于2018-12-23 15:51 被阅读12次

1.PropertyEditor接口

A PropertyEditor class provides support for GUIs that want to allow users to edit a property value of a given type.

简单说就是字符串和其他对象的类型转换器,通过setAsText设置,再通过getValue获取转换值

    @Test
    public void testStandardURI() throws Exception {
        PropertyEditor urlEditor = new URLEditor();
        urlEditor.setAsText("mailto:juergen.hoeller@interface21.com");
        Object value = urlEditor.getValue();
        assertTrue(value instanceof URL);
        URL url = (URL) value;
        assertEquals(url.toExternalForm(), urlEditor.getAsText());
    }

2.PropertyEditorRegistry

PropertyEditor注册器,用户为某类型注册PropertyEditor,PropertyEditorRegistrySupport是其默认实现类

    @Test
    public void test1()
    {
        PropertyEditorRegistrySupport registrySupport=new PropertyEditorRegistrySupport();

        registrySupport.registerCustomEditor(String.class, "name", new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue("prefix" + text);
            }
        });

        PropertyEditor propertyEditor=registrySupport.findCustomEditor(String.class, "name");
    }

3.BeanWrapper和PropertyEditor

BeanWrapper继承自PropertyEditorRegistrySupport

通过注册registerCustomEditor方法注册PropertyEditor,在调用setPropertyValue时会调用PropertyEditor的setAsText方法

    @Test
    public void testCustomEditorForSingleProperty() {
        TestBean tb = new TestBean();
        BeanWrapper bw = new BeanWrapperImpl(tb);
        bw.registerCustomEditor(String.class, "name", new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue("prefix" + text);
            }
        });
        bw.setPropertyValue("name", "value");
        bw.setPropertyValue("touchy", "value");
        assertEquals("prefixvalue", bw.getPropertyValue("name"));
        assertEquals("prefixvalue", tb.getName());
        assertEquals("value", bw.getPropertyValue("touchy"));
        assertEquals("value", tb.getTouchy());
    }

4.TypeConverter

TypeConverter简化为一个方法进行值转换,TypeConverterSupport内部使用TypeConverterDelegate实现转换,TypeConverterDelegate内部则依赖PropertyEditorRegistrySupport,所以依赖路径为

TypeConverter->TypeConverterSupport->TypeConverterDelegate->PropertyEditorRegistrySupport->PropertyEditor

    @Test
    public void test1()
    {
        SimpleTypeConverter converter=new SimpleTypeConverter();
        URL url=converter.convertIfNecessary("http://www.springframework.org",URL.class);
        System.out.println(url.toString());
    }

参考:
https://www.jianshu.com/p/6ab3e99b1b33

相关文章

网友评论

      本文标题:spring笔记-PropertyEditor

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