PropertyEditor&Converter

来源:https://blog.csdn.net/f641385712/category_10625150.html

PropertyEditor示例

package com.zzhua.test;

import org.junit.Test;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.PropertyEditorRegistrySupport;
import org.springframework.beans.propertyeditors.CharsetEditor;
import org.springframework.beans.propertyeditors.UUIDEditor;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceEditor;

import java.beans.PropertyEditor;
import java.io.IOException;
import java.util.UUID;

public class EditorTest {
    
    

    @Test
    public void test_01() {
    
    
        // 虽然都行,但建议你规范书写:UTF-8
        PropertyEditor editor = new CharsetEditor();
        editor.setAsText("UtF-8"); // 调用了Charset.forName(text)返回Charset对象
        System.out.println(editor.getAsText()); // UTF-8
        editor.setAsText("utF8"); // 调用了Charset.forName(text)返回Charset对象
        System.out.println(editor.getAsText()); // UTF-8
    }

    @Test
    public void test_02() {
    
    
        // 支持标准URL如file:C:/myfile.txt,也支持classpath:myfile.txt
        // 同时还支持占位符形式
        PropertyEditor editor = new ResourceEditor(
                // DefaultResourceLoad用来加载该资源,返回该资源封装成的Resource对象
                // StandardEnvironment添加了System.env()和System.properties作为属性源
                new DefaultResourceLoader(), new StandardEnvironment(), true);

        // file:形式
        editor.setAsText("file:D:\\Projects\\practice\\spring-annotation\\src\\main\\resources\\properties\\config.txt");
        System.out.println(editor.getAsText());
        // 输出:file:D:/Projects/practice/spring-annotation/src/main/resources/properties/config.txt
        try {
    
    
            System.out.println(((Resource) editor.getValue()).getFile().exists()); // true
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

        editor.setAsText("file:D:/Projects/practice/spring-annotation/src/main/resources/properties/config.txt");
        System.out.println(editor.getAsText());
        // 输出:file:D:/Projects/practice/spring-annotation/src/main/resources/properties/config.txt
        try {
    
    
            System.out.println(((Resource) editor.getValue()).getFile().exists()); // true
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

        // classpath形式(注意:若文件不存在不会报错,而是输出null)
        editor.setAsText("classpath:properties/db.properties");
        System.out.println(editor.getAsText());
        // 输出:file:/D:/Projects/practice/spring-annotation/target/classes/properties/db.properties

        System.setProperty("myFile.name", "properties/db.properties");
        editor.setAsText("classpath:${myFile.name}"); //
        System.out.println(editor.getAsText()); // env中有属性源: System.getProperties() 所以可解析
        // 输出:file:/D:/Projects/practice/spring-annotation/target/classes/properties/db.properties

    }

    @Test
    public void test_03() {
    
    
        PropertyEditorRegistry propertyEditorRegistry = new PropertyEditorRegistrySupport();
        // 将PropertyEditor属性编辑器注册到注册中心
        propertyEditorRegistry.registerCustomEditor(Animal.class, new AnimalPropertyEditor());

        // 父类型、子类型均可匹配上对应的编辑器
        //    1. Cat继承自Animal
        //    2. 第二个参数是PropertyPath
        PropertyEditor customEditor1 = propertyEditorRegistry.findCustomEditor(Cat.class, null);
        PropertyEditor customEditor2 = propertyEditorRegistry.findCustomEditor(Animal.class, null);
        System.out.println(customEditor1 == customEditor2);           // true
        System.out.println(customEditor1.getClass().getSimpleName()); // AnimalPropertyEditor

        // 拿到对应的propertyEditor(pe)之后,就可以调用pe.setAsText(text),经过处理之后,再拿出值pe.getValue()
    }

    @Test
    public void test_04() {
    
    
        PropertyEditorRegistry propertyEditorRegistry = new PropertyEditorRegistrySupport();
        // 通用的
        propertyEditorRegistry.registerCustomEditor(UUID.class, new UUIDEditor());
        // 专用的 (传入propertyPath) (背景:Person类有个cat属性,Cat类有个uuid属性)
        propertyEditorRegistry.registerCustomEditor(Person.class, "cat.uuid", new PersonCatUUIDEditor());


        String uuidStr = "1-2-3-4-5";
        String personCatUuidStr = "1-2-3-4-5_YourBatman";

        // 找到对应的propertyEditor(不带propertyPath)
        PropertyEditor customEditor = propertyEditorRegistry.findCustomEditor(UUID.class, null);
        customEditor.setAsText(uuidStr);
        System.out.println(customEditor.getAsText());

        // 找到对应的propertyEditor(带propertyPath)
        customEditor = propertyEditorRegistry.findCustomEditor(Person.class, "cat.uuid");
        customEditor.setAsText(personCatUuidStr);
        System.out.println(customEditor.getAsText());
    }

}

Converter示例

package org.springframework.core.convert.support;

import org.junit.Test;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class ConverterTest {
    
    
    /**
     * Converter:1:1
     */
    @Test
    public void test_01() {
    
    
        System.out.println("非public仅作演示 — StringToBooleanConverter");
        Converter<String, Boolean> converter = new StringToBooleanConverter();

        System.out.println(converter.convert("true")); // true
        System.out.println(converter.convert("1"));    // true

        System.out.println(converter.convert("FalSe"));// false
        System.out.println(converter.convert("off"));  // false

        // 注意:空串返回的是null
        System.out.println(converter.convert("")); // null


        System.out.println("----------------StringToBooleanConverter---------------");
        Converter<String, Charset> converter2 = new StringToCharsetConverter();
        // 中间横杠非必须,但强烈建议写上   不区分大小写
        System.out.println(converter2.convert("uTf-8")); // UTF-8
        System.out.println(converter2.convert("utF8"));  // UTF-8
    }

    /**
     * ConverterFactory:1:N
     */
    @Test
    public void test_02() {
    
    
        System.out.println("----------------StringToNumberConverterFactory---------------");
        ConverterFactory<String, Number> converterFactory = new StringToNumberConverterFactory();
        // 注意:这里不能写基本数据类型。如int.class将抛错
        System.out.println(converterFactory.getConverter(Integer.class).convert("1").getClass());
        System.out.println(converterFactory.getConverter(Double.class).convert("1.1").getClass());
        System.out.println(converterFactory.getConverter(Byte.class).convert("0x11").getClass());

        /*
        输出:
            class java.lang.Integer
            class java.lang.Double
            class java.lang.Byte
        */
    }

    @Test
    public void test_03() {
    
    
        System.out.println("----------------CollectionToCollectionConverter---------------");
        ConditionalGenericConverter conditionalGenericConverter = new CollectionToCollectionConverter(new DefaultConversionService());
        // 将Collection转为Collection(注意:没有指定泛型类型哦)
        System.out.println(conditionalGenericConverter.getConvertibleTypes());

        List<String> sourceList = Arrays.asList("1", "2", "2", "3", "4");
        TypeDescriptor sourceTypeDesp = TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(String.class));
        TypeDescriptor targetTypeDesp = TypeDescriptor.collection(Set.class, TypeDescriptor.valueOf(Integer.class));

        System.out.println(conditionalGenericConverter.matches(sourceTypeDesp, targetTypeDesp));
        Object convert = conditionalGenericConverter.convert(sourceList, sourceTypeDesp, targetTypeDesp);
        System.out.println(convert.getClass());
        System.out.println(convert);

        /*
        输出:
            [java.util.Collection -> java.util.Collection]
            true
            class java.util.LinkedHashSet
            [1, 2, 3, 4]
        */
    }



}

猜你喜欢

转载自blog.csdn.net/qq_16992475/article/details/121056577
今日推荐