SpringFramework中的BeanWrapper丶PropertyEditor

來源:互聯網
上載者:User

標籤:bind   應用   list   void   init   定義   日期類   ...   span   

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 = 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 companyFloat 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.