Spring自定义属性编辑器

Spring自定义属性编辑器
【Spring自定义属性编辑器】? 关于Spring的属性编辑器的使用

public class Student { private Long id; private String name; private Date birthday; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }

此时如果用String类型的形式为birthday赋值,则需要用到属性编辑器做一个转换

方式一: ? 自定义属性编辑器,并将其注册到CustomEditorConfigurer的customEditors中
public class CustomerPropertyEditor extends PropertyEditorSupport { SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd"); @Override public void setAsText(String text) throws IllegalArgumentException { try { Date date = sdf.parse(text); this.setValue(date); } catch (Exception e) { e.printStackTrace(); } } }


方式二: ? 使用spring的PropertyEditorRegistrar,将自定义的属性编辑器注册到CustomEditorConfigurer的customEditors中
public class CustomerPropertyEditorRegistrar implements PropertyEditorRegistrar { @Override public void registerCustomEditors(PropertyEditorRegistry registry) { registry.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy.MM.dd"),true)); } }


    推荐阅读