What is the easiest way to bind a UUID in Spring MVC, such that this works:
@RequestMapping("/MyController.myAction.mvc")
@ResponseBody
public String myAction(UUID id, String myParam)...
Using the above I currentely get the following exception:
org.springframework.beans.BeanInstantiationException:
Could not instantiate bean class [java.util.UUID]:
No default constructor found;
nested exception is java.lang.NoSuchMethodException: java.util.UUID.<init>()
There are other questions on SO that skirt around this, but none seem to answer it. I'm using Spring 3.latest (4 EA actually). I'm after the latest, simplest way to achieve this.
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>
The converter below is available in Spring Framework (core) since version 3.2.
org.springframework.core.convert.support.StringToUUIDConverter<String, java.util.UUID>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With