Связывание Spring Spring: Converter - java.lang.IllegalArgumentException: каждый объект конвертера должен реализовывать один из интерфейсов Converter ... - PullRequest
5 голосов
/ 31 января 2012

У меня есть следующий код в одном из XML-файлов конфигурации Spring:

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

  <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <bean class="org.springframework.binding.convert.converters.StringToDate">
                <property name="pattern" value="yyyy-MM-dd" />            
            </bean>
        </list>
    </property>
  </bean>

Но я получаю следующее исключение во время развертывания (в JBoss):

java.lang.IllegalArgumentException: каждый объект конвертера должен реализовывать один из интерфейсов Converter, ConverterFactory или GenericConverter

Любая идея, почему? Насколько я могусмотрите, org.springframework.binding.convert.converters.StringToDate является реализацией Converter.

ОБНОВЛЕНИЕ:

Только найдено этот ответ, который предполагает, что смешивание Converter с и PropertyEditor с может вызвать проблемы.В моем приложении есть часть, использующая PropertyEditor s, но, насколько я понимаю, в документации не говорится о каких-либо проблемах, связанных с смешением двух систем.

Трассировка стека:

Caused by: java.lang.IllegalArgumentException: Each converter object must implement one of the Converter, ConverterFactory, or GenericConverter interfaces
    at org.springframework.core.convert.support.ConversionServiceFactory.registerConverters(ConversionServiceFactory.java:106)
    at org.springframework.context.support.ConversionServiceFactoryBean.afterPropertiesSet(ConversionServiceFactoryBean.java:56)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
    ... 146 more

ОБНОВЛЕНИЕ 2:

Я изменил свой xml на:

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

  <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="my.project.StringToDate">
                <!-- org.springframework.binding.convert.converters.StringToDate DEFAULT_PATTERN = "yyyy-MM-dd" -->
                <property name="pattern" value="yyyy-MM-dd" />
            </bean>
        </set>
    </property>
  </bean>

Мой пользовательский конвертер:

package my.project;

import java.util.Date;

import org.springframework.core.convert.converter.Converter;

public class StringToDate extends org.springframework.binding.convert.converters.StringToDate implements Converter<String, Date> {

    public Date convert(String source) {

        Date date = null;

        try {
            date = (Date) convertSourceToTargetClass(getPattern(), getTargetClass());
        } catch (Exception e) {

        }

        return date;
    }

}

ОДНАКО, читая следующую ветку форума Я ожидаю, что преобразование будет работать.Если я правильно понял, они говорят, что, как только конвертер настроен правильно, он должен работать с Spring Batch, то есть ему не требуются какие-либо специальные настройки, чтобы он работал конкретно с Spring Batch.Но я все еще получаю BindException во время пакетного задания ... есть идеи почему?

См. Новую трассировку стека:

Caused by: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'target' on field 'datetimeInactive': rejected value [2011-04-27]; codes [typeMismatch.target.datetimeInactive,typeMismatch.datetimeInactive,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [target.datetimeInactive,datetimeInactive]; arguments []; default message [datetimeInactive]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'datetimeInactive'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'datetimeInactive': no matching editors or conversion strategy found]
Field error in object 'target' on field 'datetimeActive': rejected value [2011-04-27]; codes [typeMismatch.target.datetimeActive,typeMismatch.datetimeActive,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [target.datetimeActive,datetimeActive]; arguments []; default message [datetimeActive]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'datetimeActive'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'datetimeActive': no matching editors or conversion strategy found]
    at org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper.mapFieldSet(BeanWrapperFieldSetMapper.java:186)
    at org.springframework.batch.item.file.mapping.DefaultLineMapper.mapLine(DefaultLineMapper.java:42)
    at org.springframework.batch.item.file.FlatFileItemReader.doRead(FlatFileItemReader.java:179)
    ... 45 more

См. Также мой оригинальный вопрос (все еще не решено).

1 Ответ

3 голосов
/ 31 января 2012

Вы уверены, что должны использовать org.springframework.context.support.ConversionServiceFactoryBean? Это определенный класс пружины. Ожидается следующее:

org.springframework.core.convert.converter.GenericConverter
org.springframework.core.convert.converter.Converter
org.springframework.core.convert.converter.ConverterFactory

Вы пытаетесь отправить это

org.springframework.binding.convert.converters.Converter

Один из них - пружинный сердечник, другой - преобразователь пружинного потока. Вы можете попробовать создать @Service самостоятельно

@Service("conversionService")
public class MyConversionService extends DefaultConversionService {

    public void ConversionService() {
        addDefaultConverters();
    }

    @Override
    protected void addDefaultConverters() {
        super.addDefaultConverters();
    }

}
...