How to configure Spring ConversionService with java config?
Solution 1
From my point of view your problem is the Bean
name. Once you don't explicit set the name using @Bean(name="conversionService")
the name that will be used is getConversionService
.
From documentation:
The name of this bean, or if plural, aliases for this bean. If left unspecified the name of the bean is the name of the annotated method. If specified, the method name is ignored.
Solution 2
In SpringMVC you can extend WebMvcConfigurerAdapter and use it for Java based config. To register custom converters you can modify the "addFormatters"-Method like this
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "..." })
public class ApplicationConfiguration extends WebMvcConfigurerAdapter
{
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
{
configurer.enable();
}
@Bean
public InternalResourceViewResolver getInternalResourceViewResolver()
{
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void addFormatters(FormatterRegistry formatterRegistry)
{
formatterRegistry.addConverter(getMyConverter());
}
@Bean
public StringToCounterConverter getMyConverter()
{
return new StringToCounterConverter();
}
}
Tadas Šubonis
Updated on June 14, 2022Comments
-
Tadas Šubonis about 2 years
I have such xml:
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="converters.AddressToStringConverter" /> <bean class="converters.StringToAddressConverter" /> </list> </property> </bean>
It configures converters without problems.
But then this code fails to make the same:
@Configuration public class ConversionConfiguration { @Bean public ConversionService getConversionService() { ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean(); bean.setConverters(getConverters()); bean.afterPropertiesSet(); ConversionService object = bean.getObject(); return object; } private Set<Converter> getConverters() { Set<Converter> converters = new HashSet<Converter>(); converters.add(new AddressToStringConverter()); converters.add(new StringToAddressConverter()); return converters; } }
This piece of configuration gets scanned by context - I checked it with debugger. Where could be the problem?