我的问题与以下课程有关:

public class MyClass {
    private LocalDateTime startDate;
}


我正在尝试使用Spring XML配置设置此bean的startDate属性:

<property name="startDate">
   <value>2000-01-01</value>
</property>


我收到一个错误:

Cannot convert value of type [java.lang.String] to required type [java.time.LocalDateTime] for property 'startDate'


是否可以使用Spring进行此转换?我在net上找到了如何对Date对象执行此操作的示例,但是,LocalDateTime没有构造函数接受字符串(解决方案似乎需要这种构造函数)。通过使用静态方法LocalDateTime.parse构造LocalDateTime。

使用注释@DateTimeFormat,例如:

public class MyClass {
    @DateTimeFormat(iso=ISO.LOCAL_DATE_TIME)
    private LocalDateTime startDate;
}


这不是解决方案,因为MyClass必须在Spring之外可用。

提前致谢

最佳答案

您可以注册您的转化。像下面的代码一样,下面的代码会将字符串转换为LocalDateTime

class CustomLocalDateTimeEditor extends PropertyEditorSupport {

private final boolean allowEmpty;
private final int exactDateLength;

public CustomLocalDateTimeEditor( boolean allowEmpty) {
    this.allowEmpty = allowEmpty;
    this.exactDateLength = -1;
}

public CustomLocalDateTimeEditor(boolean allowEmpty, int exactDateLength) {
    this.allowEmpty = allowEmpty;
    this.exactDateLength = exactDateLength;
}

@Override
public void setAsText(String text) throws IllegalArgumentException {
    if (this.allowEmpty && !StringUtils.hasText(text)) {
        setValue(null);
    }
    else if (text != null && this.exactDateLength >= 0 && text.length() != this.exactDateLength) {
        throw new IllegalArgumentException("Could not parse date: it is not exactly" + this.exactDateLength + "characters long");
    }
    else {
        try {
            setValue(LocalDateTime.parse(text));
        }
        catch (DateTimeParseException ex) {
            throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
        }
    }
}

@Override
public String getAsText() {
    LocalDateTime value = LocalDateTime.parse(String.valueOf(getValue()));
    return (value != null ? value.toString() : "");
}


}

关于java - 如何在Spring XML配置中设置LocalDateTime,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31956422/

10-12 05:25