{"id":1402,"date":"2013-04-07T19:16:29","date_gmt":"2013-04-08T00:16:29","guid":{"rendered":"http:\/\/unitstep.net\/?p=1402"},"modified":"2013-04-07T19:16:29","modified_gmt":"2013-04-08T00:16:29","slug":"spring-mvc-request-parameter-conversion-with-minimal-configuration","status":"publish","type":"post","link":"https:\/\/unitstep.net\/blog\/2013\/04\/07\/spring-mvc-request-parameter-conversion-with-minimal-configuration\/","title":{"rendered":"Spring MVC request parameter conversion with minimal configuration"},"content":{"rendered":"
I’ve been playing around with Spring Web MVC a bit and was looking for something similar to Jersey’s Parameter Classes<\/a> that would provide conversion to custom types. I liked how with Jersey, you could encapsulate the conversion logic in a single class and have that reused across multiple methods with minimal configuration.<\/p>\n Here’s how I achieved a similar result in Spring Web MVC. (Note: the following examples were done with Spring 3.2.1<\/em>)<\/p>\n <\/p>\n Spring does provide some build-in support for conversion to specific types. For example, you can convert to Date and various numeric types<\/a>. But, what if you want to convert a request parameter to some other custom type or a type from a third party? (Such as the date-time classes from Joda Time<\/a>)<\/p>\n I searched for a bit and found<\/a> various<\/a> solutions<\/a>, but they all seemed to require too much configuration: In addition to writing a converter class, you’d have to manually the converter with a ConversionService (either in code or in XML<\/acronym><\/a> configuration). I didn’t like the idea of having to register the converter class; instead, I wanted it to be registered automatically based on some annotations.<\/p>\n Here’s what I came up with, based on this answer on Stack Overflow<\/a>.<\/p>\n This is so it will be available for injection via Built-in?<\/h2>\n
Minimize configuration<\/h2>\n
Solution<\/h2>\n
\n
Define a custom annotation for your converters so they can be automatically found<\/h3>\n
@Target({ ElementType.TYPE, ElementType.FIELD })\r\npublic @interface MyConverter {\r\n}<\/code><\/pre>\n<\/li>\n
Create a converter class, annotated with your custom annotation and
@Component<\/code><\/h3>\n
@Resource<\/code>. (In this example, we convert to a Joda Time
LocalDate<\/a><\/code>)<\/p>\n