Wilhelm Kleu
Wilhelm Kleu

Reputation: 11047

Spring's conversion service not calling converter to String (for display purposes)

I am using Spring webflow.

I have a FormattingConversionService configured. In this conversion service I have the following configured:

The 'ConverterFactory` is called and works perfectly.

My problem is that the Converter is not called. The toString() is displayed on the page.

How can I get Spring to convert object instance of MyInterface to String for display purposes?

Here is my conversionService declaration:

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="myclasses.StringToMyInterfaceConverterFactory"/>
            <bean class="myclasses.MyInterfaceToStringConverter"/>
        </set>
    </property>
</bean>

MyInterfaceToStringConverter:

@Component
public class MyInterfaceToStringConverter<T extends MyInterface> implements Converter<T, String> {

    public String convert(T source) {
        if (source == null) {
            return null;
        }
        return source.getCode(); // This is a method in MyInterface which returns a String
    }
}

Upvotes: 1

Views: 1237

Answers (1)

naXa stands with Ukraine
naXa stands with Ukraine

Reputation: 37936

The example of working ConversionService configuration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <!-- Enables the Spring MVC @Controller programming model -->
    <mvc:annotation-driven conversion-service="conversionService" />

    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="myclasses.StringToMyInterfaceConverterFactory" />
                <bean class="myclasses.MyInterfaceToStringConverter" />
            </set>
        </property>
    </bean>
</beans>

Upvotes: 1

Related Questions