Using Spring mvc-3. I am writing a custom Converter which needs access to other Converters registered to a ConversionService.
How can I accomplish this? I tried writing my custom converter as:
class CustomConverter<X, Y>{
@Autowired ConversionService service;
//+getter & setters of service
public Y convert(X input){
// I need access to service to lookup simple conversions such as
// String array to Long array etc..
}
}
And I registered my custom converter via applicationContext.xml
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name = "converters">
<list>
<bean class="CustomConverter"/>
</list>
</property>
</bean>
However, spring refuses to inject service into my CustomConverter(its always null). How can I accomplish this?
Thank you!
I have come across same problem. There's an issue SPR-6415 in Spring JIRA covering this problem. I've giving here my solution based on discussion in this issue. It's the same principle like answer of @nmervaillie but you don't have to implement your own ConversionServiceFactoryBean
.
/**
* Base class of @{code Converter} that need to use {@code ConversionService}.
* Instances of implementing classes must be spring-managed to inject ConversionService.
*
* @author Michal Kreuzman
*/
public abstract class CoversionServiceAwareConverter<S, T> implements Converter<S, T> {
@Inject
private ConversionService conversionService;
protected ConversionService conversionService() {
return conversionService;
}
/**
* Add this converter to {@code ConverterRegistry}.
*/
@SuppressWarnings("unused")
@PostConstruct
private void register() {
if (conversionService instanceof ConverterRegistry) {
((ConverterRegistry) conversionService).addConverter(this);
} else {
throw new IllegalStateException("Can't register Converter to ConverterRegistry");
}
}
}
@Component
public class SampleConverter extends CoversionServiceAwareConverter<Object, Object> {
@Override
public String convert(Object source) {
ConversionService conversionService = conversionService();
// Use conversionService and convert
}
}
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