I searched for the below problem, but couldn\'t find an answer.
I want to use spring\'s conversion service by writing my custom converter that implements org.spri
To resolve any circular dependencies, here the steps I followed (Spring Boot v5.2.1):
Register a simple conversionService
@Configuration
public class ConverterProvider {
@Bean
public ConversionService conversionService() {
ConversionService conversionService = new GenericConversionService();
return conversionService;
}
}
Inject your custom converters
@Component
public class ConvertersInjection {
@Autowired
private GenericConversionService conversionService;
@Autowired
private void converters(Set<Converter> converters) {
converters.forEach(conversionService::addConverter);
}
}
The converter can even autowire your conversionService
@Component
public class PushNotificationConverter implements Converter<PushNotificationMessages.PushNotification, GCM> {
@Lazy
@Autowired
private ConversionService conversionService;
@Override
public GCM convert(PushNotificationMessages.PushNotification source) {
GCM gcm = new GCM();
if (source.hasContent()) {
PushNotificationMessages.PushNotification.Content content = source.getContent();
if (content.hasData()) {
conversionService.convert(content.getData(), gcm.getData().getClass());
} else if (content.hasNotification()) {
conversionService.convert(content.getNotification(), gcm.getNotification().getClass());
}
}
return gcm;
}
}
Came across a very interesting way to do this in Stackoverflow - https://stackoverflow.com/a/12760579/204788
Using a feature called Collection merging, you can essentially do this:
<bean id="customConversionService" class="org.springframework.context.support.ConversionServiceFactoryBean" parent="conversionService">
<property name="converters">
<list merge="true">
<bean id="StringToLoggerConverter" class="com.citi.spring.converter.LoggerConverter" />
</list>
</property>
</bean>
write a custom conversionService
public class CustomerConversionServiceFactoryBean extends ConversionServiceFactoryBean {
List<Converter<Object, Object>> converters = new ArrayList<>();
public CustomerConversionServiceFactoryBean() {
super();
DefaultConversionService conversionservice = (DefaultConversionService) super.getObject();
for(int i=0;i<converters.size();i++){
conversionservice.addConverter(converters.get(i));
}
}
}
then change your xml
<bean id="conversionService"
class="CustomerConversionServiceFactoryBean" >
<property name="converters" >
<list>
<bean class="CustomConverter" />
</list>
</property>
</bean>
I think this will help you...