Spring Custom Formatter

Custom formatter are use for field formatting. The implementation is easy as my previous post spring 3 type conversion. Let’s get started with the same Holiday pojo example.

 

@Entity
@Table(name = "holiday")
@Configurable
public class Holiday {

    @Id
    @Column(name = "id", length = 15)
    private String id;

    @Id
    @Column(name = "holiday")
    @DateTimeFormat(pattern="dd-MM-yyyy")
    private Calendar holiday;

    public Holiday() {

    }

    public String getId() {
        return id;
    }

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

    public Calendar getHoliday() {
        return holiday;
    }

    public void setHoliday(Calendar holiday) {
        this.holiday = holiday;
    }

}

 

2) Next, create a class formatter for every pojo field, as long as it’s met the requirement, it will perform the formatting.

//... code omitted

public class ApplicationFormatter extends FormattingConversionServiceFactoryBean {

	private static final Logger LOG = LoggerFactory.getLogger(ApplicationFormatter.class);

	private static final String DATE_PATTERN = "dd-MM-yyyy";

	private DateTimeFormatter dateFormat;

	private Set<Formatter<?>> formatters = new HashSet<Formatter<?>>();

	@PostConstruct
	public void init() {
		dateFormat = DateTimeFormat.forPattern(DATE_PATTERN);
		formatters.add(getCalendarFormatter());
		setFormatters(formatters);
	}

	public Formatter<Calendar> getCalendarFormatter() {
		return new Formatter<Calendar>() {

			public Calendar parse(String strDate, Locale locale) throws java.text.ParseException {
				Calendar calendar = dateFormat.parseDateTime(strDate).toCalendar(locale);
				return calendar;
			}

			public String print(Calendar calendar, Locale locale) {
				DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
				return formatter.format(calendar.getTime());
			}
		};
	}

}

 

3) Next configure application context.

<?xml version="1.0" encoding="UTF-8"?>

//... code omitted
<context:annotation-config/>

<bean id="conversionService" class="com.codeomitted.fomatter.ApplicationFormatter" /> 

<bean id="publicHoliday" class="com.codeomitted.model.Holiday"
        p:id="independent"
        p:holiday="31-08-2013"/>

</beans>

 

4) Run the application now.

public static void main(String[] args) {
	GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
	ctx.load("classpath:application-validation-editor.xml");
	ctx.refresh();

	ConversionService cs = ctx.getBean("conversionService", ConversionService.class);
	Holiday pubHoliday = ctx.getBean("publicHoliday", Holiday.class);

	System.out.println(cs.convert(pubHoliday.getHoliday(), String.class));

	System.out.println(pubHoliday.getId());
	System.out.println(pubHoliday.getHoliday());

}

 

5) Result

31-08-2013

independent

java.util.GregorianCalendar[time=1377878400000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id=”Asia/Kuala_Lumpur”,offset=28800000,dstSavings=0,useDaylight=false,transitions=10,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2013,MONTH=7,WEEK_OF_YEAR=35,WEEK_OF_MONTH=5,DAY_OF_MONTH=31,DAY_OF_YEAR=243,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=5,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=28800000,DST_OFFSET=0]

Write a Reply or Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.