Spring Batch - 如何将String从文件转换为Date? [英] Spring Batch - how to convert String from file to Date?

查看:119
本文介绍了Spring Batch - 如何将String从文件转换为Date?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试处理一个CSV文件,其中某些字段是yyyy-MM-dd格式的日期 - 但是当它尝试时读取器失败将CSV文件中的字符串转换为模型类中的日期。

I am trying to process a CSV file in which some of the fields are dates of the format "yyyy-MM-dd" - but the reader fails when it tries to convert the String from the CSV file to a Date in my model class.

错误是:


org.springframework.validation.BindException:
org.springframework.validation.BeanPropertyBindingResult:1 error
字段'datetimeInactive'中对象'target'中的字段错误:拒绝
值[2011-04-27];代码
[typeMismatch.target.datetimeInactive,typeMismatch.datetimeInactive,typeMismatch.java.util.Date,typeMismatch];
参数
[org.springframework.context.support.DefaultMessageSourceResolvable:
codes [target.datetimeInactive,datetimeInactive];参数[];
默认消息[datetimeInactive]];默认消息[无法将
将类型'java.lang.String'的属性值转换为必需类型
'java.util.Date',用于属性'datetimeInactive';嵌套异常是
java.lang.IllegalStateException:无法将
[java.lang.String]类型的值转换为属性
'datetimeInactive'的必需类型[java.util.Date]:否匹配的编辑器或转换策略]

org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 error 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]

读者的XML:

http://code.google.com/p/springbatch-in-action/source/browse/trunk/sbia/ch07/src/test/resources /com/manning/sbia/ch07/test-batch-reader-context.xml?r=145

在我的XML配置文件中,我有以下内容bean:

In my XML config files I have the following beans:

  <bean id="dateEditor" class="org.springframework.beans.propertyeditors.CustomDateEditor">
    <constructor-arg>
      <bean class="java.text.SimpleDateFormat">
        <constructor-arg value="yyyy-MM-dd" />
      </bean>
    </constructor-arg>
    <constructor-arg value="true" />
  </bean>

  <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="customEditors">
      <map>
        <entry key="java.util.Date">
          <ref local="dateEditor" />
        </entry>
      </map>
    </property>
  </bean>

我的问题是:


  1. 我在我的上下文中定义了一个 CustomDateEditor - 为什么Spring不能将String转换为Date?

  1. I have defined a CustomDateEditor in my context - so why cannot Spring convert the String into Date?

我已经读过在Spring 3中有一种更新的方法( Converter ?)来完成转换。即 http://forum.springsource.org/ showthread.php?108480-Register-TypeConverter-PropertyEditor-w-Spring-Batch - 但是,我在Spring Batch文档中找不到任何示例代码。你能在这里看一下如何做/点我链接吗?

I have read that there is a newer way in Spring 3 (Converter ?) to get the conversion done. i.e. http://forum.springsource.org/showthread.php?108480-Register-TypeConverter-PropertyEditor-w-Spring-Batch -- however, I could not find any example code to this in the Spring Batch documentation. Could you show here how to do it / point me out to some link?

UPDATE:

我得到了问题#2的答案:

I've got an answer to question #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;
    }

}

我仍在寻找答案问题#1。即,在设置转换器之后,我仍然在批处理任务期间获得BindException。来自这个论坛帖子,看起来我的代码应该已经执行了转换。

I am still looking for an answer to question #1. I.e., after setting the converter, I am still getting BindException during the batch task. From this forum thread, it looks like my code should have performed the conversion.

堆栈跟踪是:

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


推荐答案

您的论坛参考用于构建应用程序上下文和配置bean时的类型转换

your forum reference is for type conversion while building the application context and configuring the beans

看一下JavaDoc的 BeanWrapperFieldSetMapper

take a look at the JavaDoc for the BeanWrapperFieldSetMapper


要自定义FieldSet值转换为所需的
类型以便注入原型的方式,有几种选择。您
可以直接通过customEditors
* 属性 *注入PropertyEditor实例,或者您可以覆盖createBinder(Object)和
initBinder (DataBinder)方法,或者你可以提供一个自定义的FieldSet
实现。

To customize the way that FieldSet values are converted to the desired type for injecting into the prototype there are several choices. You can inject PropertyEditor instances directly through the customEditors *property*, or you can override the createBinder(Object) and initBinder(DataBinder) methods, or you can provide a custom FieldSet implementation.

意味着你应该将你的CustomDateEditor直接注入到Mapper

meaning you should inject your CustomDateEditor directly into the Mapper

这篇关于Spring Batch - 如何将String从文件转换为Date?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆