首页 > 代码库 > SpringFramework中的BeanWrapper丶PropertyEditor

SpringFramework中的BeanWrapper丶PropertyEditor

BeanWrapper是org.springframework.beans包下的一个借口,对应的实现类为BeanWrapperImpl,提供对应的get/set方法,并且设置属性的可读性和可写性。

public class Company {

    private String name;
    private Employee managingDirector;

    public String getName() {
        return this.name;
    }

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

    public Employee getManagingDirector() {
        return this.managingDirector;
    }

    public void setManagingDirector(Employee managingDirector) {
        this.managingDirector = managingDirector;
    }
}
public class Employee { private String name; private float salary; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public float getSalary() { return salary; } public void setSalary(float salary) { this.salary = salary; } }
BeanWrapper company = new BeanWrapperImpl(new Company()); // setting the company name.. company.setPropertyValue("name", "Some Company Inc."); // ... can also be done like this: PropertyValue value = http://www.mamicode.com/new PropertyValue("name", "Some Company Inc."); company.setPropertyValue(value); // ok, let‘s create the director and tie it to the company: BeanWrapper jim = new BeanWrapperImpl(new Employee()); jim.setPropertyValue("name", "Jim Stravinsky"); company.setPropertyValue("managingDirector", jim.getWrappedInstance()); // retrieving the salary of the managingDirector through the company Float salary = (Float) company.getPropertyValue("managingDirector.salary");
从以上这些代码看一看出来,BeanWrapper可以看成是POJOs转化为bean之后的父类型。

  Spring中引出PropertyEditor的概念,主要是为了实现String类型与其他类型的转化。最常见的就是String类型和日期类型的转换,CustomDateEditor是面向java.util.Data
专门的属性编辑器,支持常用的DataFormat。在实际操作中经常会碰到表单中的日期 字符串和Javabean中的日期类型的属性自动转换, 而springMVC默认不支持这个格式的转换,所以必
须要手动配置, 自定义数据类型的绑定才能实现这个功能。比较简单的可以直接应用springMVC的注解@initbinder和spring自带的WebDataBinder类和操作。
@InitBinder
public void initBinder(WebDataBinder binder) {
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  dateFormat.setLenient(false);
  binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
  
  

 
 

SpringFramework中的BeanWrapper丶PropertyEditor