Sunday, April 24, 2016

Spring CustomEditorConfigurer

When doing DI, some format of property will need to transfer.

The target property is java.util.Date, but we can only inject String "2016-04-24"
<property name="date" value="2016-04-24"></property>
So we need a customEditorConfigurer

 <bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
  <property name="customEditors">
   <!-- key: target property's class -->
   <!-- value: PropertyEditor bean -->
<entry key="java.util.Date">
     <!-- Inner Bean -->
     <bean class="com.gvace.util.DatePropertyEditor">
      <property name="format" value="yyyy-MM-dd"></property>
 <!-- Use inner Bean instead -->
 <!-- <bean id="datePropertyEditor" class="com.gvace.util.DatePropertyEditor"></bean>  -->

Create custom PropertyEditor, which extends PropertyEditorSupport
package com.gvace.util;

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

//extends PropertyEditorSupport
public class DatePropertyEditor extends PropertyEditorSupport{
 private String format;
 public void setAsText(String text) throws IllegalArgumentException {
  try {
   Date date = new SimpleDateFormat(format).parse(text);
  } catch (ParseException e) {
   throw new IllegalArgumentException("IllegalArgumentException"+text);
 public String getFormat() {
  return format;
 public void setFormat(String format) {
  this.format = format;

No comments:

Post a Comment