Register Spring Converter Programmatically in Spring Boot
Here is my solution:
A TypeConverter Annotation:
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface TypeConverter {
}
A Converter Registrar:
@Configuration
public class ConverterConfiguration {
@Autowired(required = false)
@TypeConverter
private Set<Converter<?, ?>> autoRegisteredConverters;
@Autowired(required = false)
@TypeConverter
private Set<ConverterFactory<?, ?>> autoRegisteredConverterFactories;
@Autowired
private ConverterRegistry converterRegistry;
@PostConstruct
public void conversionService() {
if (autoRegisteredConverters != null) {
for (Converter<?, ?> converter : autoRegisteredConverters) {
converterRegistry.addConverter(converter);
}
}
if (autoRegisteredConverterFactories != null) {
for (ConverterFactory<?, ?> converterFactory : autoRegisteredConverterFactories) {
converterRegistry.addConverterFactory(converterFactory);
}
}
}
}
And then annotate your converters:
@SuppressWarnings("rawtypes")
@TypeConverter
public class StringToEnumConverterFactory implements ConverterFactory<String, Enum> {
@SuppressWarnings("unchecked")
public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
return new StringToEnum(targetType);
}
private final class StringToEnum<T extends Enum> implements Converter<String, T> {
private Class<T> enumType;
public StringToEnum(Class<T> enumType) {
this.enumType = enumType;
}
@SuppressWarnings("unchecked")
public T convert(String source) {
return (T) Enum.valueOf(this.enumType, source.trim().toUpperCase());
}
}
}
**If you are not on Spring Boot, where automatic registration of converters annotated with @Component (and similar stereotype annotations) is performed and you are not in Web Mvc environment :
@Bean
ConversionService conversionService(){
ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean();
Set<Converter<?, ?>> convSet = new HashSet<Converter<?, ?>>();
convSet.add(new MyConverter()); // or reference bean convSet.add(myConverter());
factory.setConverters(convSet);
factory.afterPropertiesSet();
return factory.getObject();
}
The answer is, you only need to anotate your converter as @Component
:
This is my converter example
import org.springframework.core.convert.converter.Converter;
@Component
public class DateUtilToDateSQLConverter implements Converter<java.util.Date, Date> {
@Override
public Date convert(java.util.Date source) {
return new Date(source.getTime());
}
}
Then when Spring needs to make convert, the converter is called.
My Spring Boot Version: 1.4.1