Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure Spring ConversionService with java config?

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?

like image 962
Tadas Šubonis Avatar asked Jun 30 '12 10:06

Tadas Šubonis


People also ask

How do I use Conversionservice?

Method SummaryReturn true if objects of sourceType can be converted to the targetType . Return true if objects of sourceType can be converted to the targetType . Convert the given source to the specified targetType . Convert the given source to the specified targetType .

What is the use of @configuration in spring boot?

One of the most important annotations in spring is @Configuration annotation which indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application. This annotation is part of the spring core framework.


1 Answers

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.

like image 129
Francisco Spaeth Avatar answered Nov 07 '22 07:11

Francisco Spaeth