spring笔记-PropertyEditor

1.PropertyEditor接口

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

spring笔记-PropertyEditor_第1张图片

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

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

2.PropertyEditorRegistry

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

spring笔记-PropertyEditor_第2张图片
    @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

spring笔记-PropertyEditor_第3张图片
spring笔记-PropertyEditor_第4张图片

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());
    }
spring笔记-PropertyEditor_第5张图片

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

你可能感兴趣的:(spring笔记-PropertyEditor)