Bind UUID in Spring MVC

The converter below is available in Spring Framework (core) since version 3.2.

org.springframework.core.convert.support.StringToUUIDConverter<String, java.util.UUID>

UUID is a class that cannot simply be instantiated. Assuming that it comes as a request parameter you should first annotate the argument with @RequestParam.

@RequestMapping("/MyController.myAction.mvc")
@ResponseBody
public String myAction(@RequestParam UUID id, String myParam)...

Now this expects a request parameter with the name id to be available in the request. The parameter will be converted to a UUID by the StringToUUIDConverter which is automatically registered by Spring.


Prior to the Spring 3.2

there was no StringToUUIDConverter so additionally you have to write and register converter by your own.

public class StringToUUIDConverter implements Converter<String, UUID> {
    public UUID convert(String source) {
        return UUID.fromString(source);
    }
}

Hook this class up to the ConversionService and you should have UUID conversion for request parameters. (This would also work if it was a request header, basically for everything that taps into the ConversionService). You also might want to have a Converter for the other-way (UUID -> String).

Hooking it up to Spring MVC is nicely explained in the reference guide (assuming you use xml config). But in short:

<mvc:annotation-driven conversion-service="conversionService"/>

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="org.company.converter.StringToUUIDConverter"/>
        </set>
    </property>
</bean>