Spring Framework 3.0 and Annotation-driven Formatting

Thursday Apr 29th 2010 by Jim White

Learn how to use the new formatting annotations in Spring Framework 3.0 to improve the appearance of numeric, date and time information.

Spring Framework 3.0 was released in late 2009 with many new and powerful features. While additions such as Spring Expression Language (SpEL), support for RESTful Web services, and the expansion of stereotype and annotated-based components get the lion's share of attention, not all the new features are as major. Some of the real convenience features take very little time to learn and you can incorporate them in your applications in no time. In this article, I introduce you to one such Spring 3 feature: annotation-driven formatting.

Introducing Formatting Annotations

Spring 3 offers two new annotations that you can use to format numbers, date, and time bean properties and method parameters: @NumberFormat and @DateTimeFormat. You can use @NumberFormat to format any numeric primitives or java.lang.Number instances (such as BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short). You can use @DateTimeFormat to format any java.util.Date, java.util.Calendar, java.util.Long (representing a date/time in milliseconds since the epoch January 1, 1970, 00:00:00 GMT), or Joda Time field/parameter. Joda Time is an open source package that provides a "quality replacement for the Java date and time classes."

To specify the formatting of any numeric or date/time property in your Spring bean class, simply add @NumberFormat or @DateTimeFormat to it. Take, for example, the Employee class in Listing 1. It is a simple unannotated POJO (plain old java object), the type often used as a command bean to collect and display data in HTML forms.

When used as a command bean to populate a form (using Spring Form tags), by default the form would display the data shown in Figure 1.

Figure 1. HTML Form Without Use of Formatting Annotations:
When you use an unannotated Employee command bean, Spring uses its default formatting to populate the HTML form (using Spring Form tags), resulting in less than appealing form entry.

Not very pretty, is it? Prior to the formatting annotations, developers would need to develop special getters/setters and/or use PropertyEditors to make the display of numeric and data/time properties more usable.

Adding the @NumberFormat and @DateTimeFormat formatting annotations (both from the org.springframework.format.annotation package) to the Employee class as demonstrated in Listing 2, causes the display to change dramatically (see Figure 2). Now, no special getters/setters or editors are necessary to get this type of data to display as users might expect.

Figure 2. HTML Form Displaying Numeric and Date/Time Information with Formatting:
Using the formatting annotated Employee class, the same HTML form can be used to capture and display data in a more expected format.

Annotation Options

Annotation attributes affect how both the @NumberFormat and @DateTimeFormat annotations work. The @NumberFormat annotation has two optional attributes: style and pattern. The style attribute allows you to select from one of three org.springframework.format.annotation.NumberFormat.Style enums. The table below outlines the three choices and an example of each is used in the Employee class shown in Listing 2.

NumberFormat.Style Enums Default

The style abides by the current locale. So, for example, a double field annotated with @NumberFormat(style = Style.CURRENCY) displays with a proceeding $ character in the en-us locale, but would probably be proceeded by a for the fr-fr locale.

Use the pattern attribute to specify a custom pattern for numbers. The pattern follows Java's standard numeric formatting patterns. By default, an empty string defines the pattern (suggesting no pattern is to be applied).

The @DateTimeFormat annotation also has optional attributes: style, pattern and iso. The style attribute allows you to provide a two-character string that dictates how the date and time should be formatted. The first character dictates the date formatting, and the second dictates time formatting. The table below provides a listing of the options and shows you example output.

@DateTimeFormat Style (using the same character for both date and time) String Example Output
Short form (SS is the default style) SS 8/30/64 11:24 AM
Medium form MM Aug 30, 1964 11:24:41 AM
Long form LL August 30, 1964 11:24:41 AM CDT
Full form FF Sunday, August 30, 1964 11:24:41 AM CDT
Use a dash to omit the date or time (omitting time in this example, with medium format for the date) M- Aug 30, 1964

The pattern attribute allows you to use a custom date/time pattern string to format the date and/or time. The pattern string follows the Java standard date/time formatting. Again, by default, the pattern string is empty. No formatting occurs when the pattern is an empty string.

Lastly, use the iso attribute with one of four org.springframework.format.annotation.DateTimeFormat.ISO enums to format the field by the ISO standard date/time format patterns. The table below shows the ISO enum options and example output.

Setup for Formatting Annotations

What do you need to use formatting annotations? The new formatting annotations come with Spring 3, so the appropriate Spring 3 JAR files are required. You must also inform Spring to be on the lookout for your formatting annotations by adding the annotation-driven element to your Spring bean XML configuration file as shown here.

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <mvc:annotation-driven /> </beans>

The <annotation-driven> element in the Spring XML configuration file enables automatic annotation-driven declaration.

If you use Joda to type date/time properties, you must also place the Joda JAR file on the classpath. To help you better understand and play with formatting annotations, download the source code for this article. It includes a small sample Web application, complete with the necessary Spring JAR files, XML configuration, and formatting annotated Employee class.

Parsing Parameters

You can also use the formatting annotations to inform Spring how to parse incoming data, especially for Controller methods. The example below shows how to use the @DateTimeFormat annotation to parse a path variable for time information provided in the ISO-specified format.

@RequestMapping(value = "/employeecheck/{time}", method = RequestMethod.GET) public String getEmployeesOnTheClock(@PathVariable @DateTimeFormat(iso=ISO.TIME) java.util.Date time) { ... }

Wrap Up

While many of the Spring 3 features are powerful, they can also require a fair amount of spin-up time and integration into applications. The new formatting annotations can be quickly and easily incorporated into your applications, and can actually help to reduce code and configuration like PropertyEditors. Download Spring 3 and try them today.

Code Download

  • SpringFormattingAnnotationsExample.zip
  • For Further Reading

  • Spring 3 feature overview from Juergen Hoeller (from SpringSource blog)
  • About the Author

    Jim White is the Director of Training and partner at Intertech Training.
    Mobile Site | Full Site
    Copyright 2017 © QuinStreet Inc. All Rights Reserved