19 April 2016

Spring's @Value with custom types

Everyone knows you can do:
@Value("${some.property}") String myString;
@Value("classpath:/${some.file}") Resource file;
Some know you can also do:
@Value("classpath:/myFile.txt") InputStream inputStream;
@Value("classpath:/${some.property}") Reader reader;
But what if we want to do:
@Value("some string ${with.properties}") MyObject myObject;
In this case spring will automatically look for builder methods valueOf, of, from or proper constructor (as described in ObjectToObjectConverter). So
public MyObject(String parameter) {...}
will be enough.

If more complex conversion is needed, one possibility is to create a bean named conversionService and type ConversionService with registered converters. For example:
@Bean(name="conversionService")
public ConversionService conversionService() {
    DefaultConversionService conversionService = new DefaultConversionService();
    conversionService.addConverter(String.class, MyObject.class, s -> ...);
    return conversionService;
}

Tested with spring 4.2.5.RELEASE