M
M
Maa-Kut2016-09-12 13:31:36
Spring
Maa-Kut, 2016-09-12 13:31:36

Why is Converter not picked up?

Good day to all.
Please help me with the following problem.
I have an application on Spring MVC 4.3.2. It has a controller that accepts a string parameter. For greater typing, I want to turn this string parameter into an enum. Those. having:

package my.app.enums;

public enum Option {
    OPTION_1,
    OPTION_2,
    OPTION_3;
}

I want to be able to make a controller:
@Controller
@RequestMapping("foo")
public class MyController {

    @RequestMapping("bar/{option}")
    public ModelAndView getBar(@PathVariable("option") Option option) {
        // всяко-разно
    }
}

For this purpose, I write my own converter:
import org.springframework.core.convert.converter.Converter;
import my.app.enums.Option;

public class OptionConverter implements Converter<String, Option> {
   @Override
   public Option convert(String source) {
       return Option.valueOf(source); // на самом деле, посложнее, но это не суть
   }
}

Further, in accordance with the documentation ( docs.spring.io/spring/docs/current/spring-framewor... ), I declare and configure the conversion service in the configuration XML:
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set merge="true">
            <bean class="my.app.OptionConverter"/>
        </set>
    </property>
</bean>

Finally, I go to localhost:8080/foo/bar/OPTION_1 eeee... everything fails with ConversionNotSupportedException: Spring brazenly states that it doesn't see a way to turn java.lang.Spring into my.app.enum.Option.
Putting a break in the convertIfNecessary method of the TypeConverterDelegate class, I noticed there is a certain PropertyEditorRegistrySupport. The Internet says that, for some reason, Spring did not use the conversionService at all, although under debugging it is clear that the ConversionServiceFactoryBean instance is created and its converters property is initialized.
In general, I feel that I am stuck or very stupid. Tell me, where else to dig?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evhen, 2016-09-12
@EugeneP2

The conversionService bean itself must be specified in <mvc:annotation-driven/>
Conversion and Formatting

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set merge="true">
            <bean class="my.app.OptionConverter"/>
        </set>
    </property>
</bean>

  <mvc:annotation-driven conversion-service="conversionService"/>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question