以下部分顯示如何將數(shù)據(jù)填充到j(luò)ava.util.Date類型值。
以下部分顯示如何將數(shù)據(jù)填充到j(luò)ava.util.Date類型值。...
package com.www.yjpub.cnmon;
import java.util.Date;
//from w w w . j a v a2 s . c om
public class Customer {
Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {
return "Customer [date=" + date + "]";
}
}
以下代碼顯示如何將String值解析為Date值,然后設(shè)置為Java bean。
以下代碼顯示如何將String值解析為Date值,然后設(shè)置為Java bean。...
在 constructor-arg 標(biāo)記中,它將值設(shè)置為日期屬性。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
<bean id="customer" class="com.www.yjpub.cnmon.Customer">
<property name="date">
<bean factory-bean="dateFormat" factory-method="parse">
<constructor-arg value="2010-01-31" />
</bean>
</property>
</bean>
</beans>
在第二種填充日期值的方法中,我們使用CustomDateEditor類。
在bean xml配置文件中,它聲明了一個(gè)CustomDateEditor類將String轉(zhuǎn)換為java.util.Date。
<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>
然后它聲明CustomEditorConfigurer使Spring轉(zhuǎn)換類型為java.util.Date的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>
這里是bean配置文件的完整示例。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<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>
<bean id="customer" class="com.www.yjpub.cnmon.Customer">
<property name="date" value="2010-02-31" />
</bean>
</beans>
運(yùn)行應(yīng)用程序。
package com.www.yjpub.cnmon;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"SpringBeans.xml");
Customer cust = (Customer) context.getBean("customer");
System.out.println(cust);
}
}
更多建議: