I am using Spring's Conversion Service, and have my own converter registered with it:
public class MyTypeConverter implements Converter<String, MyType> {
@Override
public Currency convert(String text) {
MyType object = new MyType();
// do some more work here...
return object;
}
}
Now in my application I can do conversion from String
to MyType
and it works well:
@Autowired
private ConversionService cs;
public void doIt() {
MyType object = cs.convert("Value1", MyType.class);
}
But I also noticed, for example, that I can use the same converter within my MVC Controller, and it does somehow work with lists too:
@RequestMapping(method = RequestMethod.GET, value = "...")
@ResponseBody
public final String doIt(@RequestParam("param1") List<MyType> objects) throws Exception {
// ....
}
So if I do submit param1=value1,value2
in controller I do receive a List<MyType>
with two elements in it. So spring does split the String by commas and then converts each element separately to MyType
. Is it possible to do this programmatically as well?
I would need something similar like this:
List<MyType> objects = cs.convert("Value1,Value2", List<MyType>.class);
Spring provides out-of-the-box various converters for built-in types; this means converting to/from basic types like String, Integer, Boolean and a number of other types. Apart from this, Spring also provides a solid type conversion SPI for developing our custom converters.
Method SummaryReturn true if objects of sourceType can be converted to the targetType . Return true if objects of sourceType can be converted to the targetType . Convert the given source to the specified targetType . Convert the given source to the specified targetType .
Spring 3.0 introduces a simple Converter interface that you can implement and reuse anywhere in Spring. You can use them in Spring MVC to convert request String values to Controller method parameter values of any Object type that you can write a Converter for.
The @Repository annotation can have a special role when it comes to converting database exceptions to Spring-based unchecked exceptions.
I found pretty close solution myself:
List<MyType> objects = Arrays.asList(cs.convert("Value1,Value2", MyType[].class));
Would be nicer if Conversion Service would create list automatically, but it is not a big overhead to use Arrays.asList()
to do it yourself.
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