January 24, 2021
Hot Topics:

Spring Framework 3.0 and Annotation-driven Formatting

  • By Jim White
  • Send Email »
  • More Articles »

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.

    Page 2 of 2

    This article was originally published on April 30, 2010

    Enterprise Development Update

    Don't miss an article. Subscribe to our newsletter below.

    Thanks for your registration, follow us on our social networks to keep up-to-date