如何在Spring xml配置文件中初始化Java Date对象?

Cod*_*lue 10 java xml configuration spring

考虑这个简单的例子 -

public class Person
 {
    private String name;
    private Date dateOfBirth;

    // getters and setters here...
 }
Run Code Online (Sandbox Code Playgroud)

为了将Person初始化为Spring bean,我可以编写以下内容.

<bean id = "Michael" class = "com.sampleDomainName.Person">
<property name = "name" value = "Michael" />
</bean>
Run Code Online (Sandbox Code Playgroud)

但是在上面的bean定义中,我该如何设置dateOfBirth?

例如.我想将dateOfBirth设置为

1998-05-07
Run Code Online (Sandbox Code Playgroud)

oxb*_*kes 7

像任何其他POJO一样对待它(这是)

<property name="dateOfBirth">
  <bean class="java.util.Date" />
</property>
Run Code Online (Sandbox Code Playgroud)

如果您需要使用显式值(例如1975-04-10),那么只需调用其中一个构造函数(尽管那些采用年度 - 月 - 日的构造函数已弃用).你也可以使用一个明确java.beans.PropertyEditor春卷已经(参见6.4.2 ;请注意,您可以编写自己的编辑和注册他们自己的类型).您需要在配置中注册CustomEditorConfigurer:

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
  <property name="customEditors">
    <map>
      <entry key="java.util.Date" 
             value="org.springframework.beans.propertyeditors.CustomDateEditor"/>
    </map>
  </property> 
</bean>
Run Code Online (Sandbox Code Playgroud)

然后你的数据看起来像:

<property name="dateOfBirth" value="1975-04-10" />
Run Code Online (Sandbox Code Playgroud)

我想补充一点,Date不是一个合适的数据类型来存储日期的出生,因为Date实在是一个即时的时间.您可能希望看看Joda并使用该LocalDate课程.


Cod*_*lue 3

这里提到的答案之一很有用,但需要更多信息。需要提供 CustomDateEditor 的构造函数参数。

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

<bean id = "customDateEditor" 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>
Run Code Online (Sandbox Code Playgroud)

现在我们可以做

<property name="dateOfBirth" value="1998-05-07" />
Run Code Online (Sandbox Code Playgroud)