This tutorial I will demonstrate how to create spring 3 type conversion by replace PropertyEditor to perform the conversion. Let’s start convert String to Calendar and print on the console. Example I have the following Holiday class.
@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() { //empty constructor } 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) Now this step is important. You must register conversionService in your application context. If no conversionService found, spring will use PropertyEditor by default.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.codeomitted.converter.StringToCalendarConverter"/> </list> </property> </bean> <bean id="publicHoliday" class="com.codeomitted.model.Holiday" p:id="independent" p:holiday="31-08-2013"/> </beans>
//... code omitted public class StringToCalendarConverter implements Converter<String, Calendar> { private DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); @Override public Calendar convert(String calendarString) { Calendar calendar = Calendar.getInstance(); try { Date date = (Date)formatter.parse(calendarString); calendar.setTime(date); } catch (Exception e) { calendar = null; } return calendar; } }
3) Create a simple java application to print the holiday object.
public class AppConversExample { public static void main(String[] args) { GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.load("classpath:application-validation-editor.xml"); ctx.refresh(); Holiday pubHoliday = ctx.getBean("publicHoliday", Holiday.class); System.out.println(pubHoliday.getId()); System.out.println(pubHoliday.getHoliday()); } }
4) Sample output
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]
5) Now convert Calendar back to String
// .. code omitted <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.codeomitted.converter.StringToCalendarConverter"/> <bean class="com.codeomitted.converter.CalendarToStringConverter"/> </list> </property> </bean> // .. code omitted
6) Create CalendarToStringConverter class
// code omitted public class CalendarToStringConverter implements Converter<Calendar, String> { private DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); @Override public String convert(Calendar calendar) { calendar.add(Calendar.DATE, 0); String strDate = formatter.format(calendar.getTime()); return strDate; } }
7) Slightly change your previous code and run again.
// .. code omitted 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()); }
8) Output
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]
9) By default conversionService support common types converting to each other. Refer example below to get some idea
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); // string to array String text = "hello world"; String arr[] = cs.convert(text, String[].class); System.out.println("arr[] length = " + arr[0]); // another string to array String arrText = "h,e,l,l,o"; String arr2[] = cs.convert(arrText, String[].class); System.out.println("arr2[0] " + arr2[0]); System.out.println("arr2[1] " + arr2[1]); System.out.println("arr2[2] " + arr2[2]); System.out.println("arr2[3] " + arr2[3]); System.out.println("arr2[4] " + arr2[4]); // array to string String newText = cs.convert(arr2, String.class); System.out.println("newText = " + newText); // String to integer int value20 = cs.convert("20", Integer.class); System.out.println("value20 = " + value20); // integer to String String number300 = cs.convert(300, String.class); System.out.println("number300 = " + number300); // enum to String String statusStr = cs.convert(Status.ACTIVE, String.class); System.out.println("statusStr = " + statusStr); // Collection List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); // list to set Set<Integer> intSet = cs.convert(list, HashSet.class); for(Integer obj: intSet) { System.out.println(obj.intValue()); } // set to list List<Integer> intList = cs.convert(intSet, ArrayList.class); for(Integer obj: intList) { System.out.println(obj); } // boolean to string boolean isTrue = true; String strTrue = cs.convert(isTrue, String.class); System.out.println("strTrue = " + strTrue); // String to boolean String falseVal = "false"; boolean booVal = cs.convert(falseVal, Boolean.class); System.out.println("boolVal = " + booVal); // Locale to String Locale aLocale = new Locale.Builder().setLanguage("fr").setRegion("CA").build(); String langCode = cs.convert(aLocale, String.class); System.out.println("langCode = " + langCode); // String to Locale String en_GB = "en_GB"; Locale enLocale = cs.convert(en_GB, Locale.class); System.out.println("Locale = " + enLocale.getCountry()); }
Pingback:CustomPropertyEditor ‹ CodeOmitted