Bind UUIDs in Spring MVC

What is the easiest way to bind UUIDs in Spring MVC, so this works:

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

Using the above, I 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 about SO that go around this, but no one seems to answer it. I am using Spring 3.latest (actually 4 EA). I follow the latest, easiest way to achieve this.

+7
java spring spring-mvc
source share
3 answers

UUID is a class that cannot be simply created. Assuming 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 it expects that the request parameter with the name id will be available in the request. The parameter will be converted to a UUID . However, at the moment this will not succeed, because there is currently nothing that can convert from String to UUID .

To do this, create a Converter that can do this.

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

Connect this class to ConversionService , and you need to convert the UUID for the request parameters. (This will also work if it's a request header, mainly for everything that comes with ConversionService ). You can also have Converter for another path (UUID -> String).

By connecting it to Spring, MVC is well explained in the reference manual (assuming you are using xml config). But in a word:

 <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> 
+15
source share

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

 org.springframework.core.convert.support.StringToUUIDConverter<String, java.util.UUID> 
+4
source share

If you use the parameter as the header parameter

 @RequestHeader(value="UUID") String id 

If his appearance in the model

 @ModelAttribute(value="ModelName") Entity modelName 
+1
source share

All Articles