Spring PropertyEditor 相關類的模擬實現

Spring xml 配置文件中的字符串值類型是如何通過 Spring的機制以正確的數據類型注入給目標屬性的?
以下主要模擬將 String 轉爲 int 、date 類型。

首先 Spring 是結合了 java.beans.BeanInfo 實現了屬性的轉換。

1、模擬的demo類

package com.jd;

import java.beans.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.stream.Stream;

public class JavaBeanDemo {

    public static void main(String[] args) {
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(Student.class, Object.class);

            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            Stream.of(propertyDescriptors).forEach(System.out::println);

            System.out.println();

            Student student = new Student();

            Stream.of(propertyDescriptors).forEach(propertyDescriptor -> {

                String propertyName = propertyDescriptor.getName();
                if ("id".equals(propertyName)) {

                    // 必須設置一下,否則會 NNP
                    propertyDescriptor.setPropertyEditorClass(IdPropertyEditor.class);

                    PropertyEditor propertyEditor = propertyDescriptor.createPropertyEditor(student);
                    Method setIdMethod = propertyDescriptor.getWriteMethod();

                    propertyEditor.addPropertyChangeListener(new SetPropertyChangeListener(student, setIdMethod));

                    propertyEditor.setAsText("99");
                }

                if ("birth".equals(propertyName)) {
                    // 必須設置一下,否則會 NNP
                    propertyDescriptor.setPropertyEditorClass(DatePropertyEditor.class);

                    PropertyEditor propertyEditor = propertyDescriptor.createPropertyEditor(student);
                    Method setBirthMethod = propertyDescriptor.getWriteMethod();

                    propertyEditor.addPropertyChangeListener(new SetPropertyChangeListener(student, setBirthMethod));

                    propertyEditor.setAsText("2017-09-01 22:00:00");
                }

            });

            System.out.println(student);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class SetPropertyChangeListener implements PropertyChangeListener {

        private Object bean;
        private Method setWriteMethod;

        public SetPropertyChangeListener(Object bean, Method setWriteMethod) {
            this.bean = bean;
            this.setWriteMethod = setWriteMethod;
        }

        @Override
        public void propertyChange(PropertyChangeEvent event) {
            PropertyEditor source = (PropertyEditor) event.getSource();
            try {
                setWriteMethod.invoke(bean, source.getValue());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

}

2、int 類型 PropertyEditor

package com.jd;

import org.springframework.util.StringUtils;

import java.beans.PropertyEditorSupport;

public class IdPropertyEditor extends PropertyEditorSupport {

    @Override
    public void setAsText(String text) throws IllegalArgumentException {

        if (StringUtils.hasText(text)) {

            int id = Integer.valueOf(text);

            setValue(id);
        }
    }

}

3、date 類型PropertyEditor

package com.jd;

import org.springframework.util.StringUtils;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DatePropertyEditor extends PropertyEditorSupport {

    @Override
    public void setAsText(String text) throws IllegalArgumentException {

        if (StringUtils.hasText(text)) {

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat();

            simpleDateFormat.applyPattern("yyyy-MM-dd HH:mm");
            try {

                Date date = simpleDateFormat.parse(text);

                setValue(date);

            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
    }

}

4、Java bean

package com.jd;

import java.util.Date;

public class Student {

    private int id;
    private String name;
    private int age;
    private Date birth;

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {

        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", birth=" + birth +
                '}';
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章