Listing 14-15. Testing Custom Formatter
package com.apress.prospring3.ch14.convserv;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.core.convert.ConversionService;
import com.apress.prospring3.ch14.domain.Contact;
public class ConvFormatServExample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:conv-format-service-app-context.xml");
ctx.refresh();
Contact clarence = ctx.getBean("clarence", Contact.class);
System.out.println("Contact info: " + clarence);
ConversionService conversionService = ctx.getBean(
"conversionService", ConversionService.class);
System.out.println("Birthdate of contact is : " +
conversionService.convert(clarence.getBirthDate(), String.class));
}
}
Running the program produces the following output:
INFO [com.apress.prospring3.ch14.convserv.factory.ApplicationConversionServiceFactoryBean] ­
<Parsing date string: 1978-08-09>
Contact info: First name: Clarence - Last name: Ho - Birth date: 1978-08-09T00:00:00.000+08:00
­ Personal site: http://www.clarence.com
INFO [com.apress.prospring3.ch14.convserv.factory.ApplicationConversionServiceFactoryBean] ­
<Formatting datetime: 1978-08-09T00:00:00.000+08:00>
Birthdate of contact is : 1978-08-09
In the output, you can see Spring uses our custom formatter's parse() method to convert the
property from a String to the DateTime type of the birthDate attribute. When we call the
ConversionService.convert() method and pass in the birthDate attribute, Spring will call the print()
method to format the output.
Validation in Spring
Validation is a critical part of any application. Validation rules applied on domain objects ensure that all
business data is well structured and fulfills all the business definitions. The ideal case is that all
validation rules are maintained in a centralized location and the same set of rules are applied to the
same type of data, no matter which source the data comes from (for example, user input via a web
application, from a remote application via web services, from a JMS message, from a file, and so on).
When talking about validation, conversion and formatting are important too, because before a piece
of data can be validated, it should be converted to the desired POJO according to the formatting rules
defined for each type.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home