SpringはBeanプロパティに日付を挿入します– CustomDateEditor
Beanプロパティに「日付」を挿入する方法を示すSpringの例。
package com.example.common; import java.util.Date; 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 + "]"; } }
Bean構成ファイル
それを実行します
package com.example.common; 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); } }
次のエラーメッセージが表示されます。
Caused by: org.springframework.beans.TypeMismatchException: Failed to convert property value of type [java.lang.String] to required type [java.util.Date] for property 'date'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'date': no matching editors or conversion strategy found
溶液
Springでは、2つの方法でDateを注入できます:
1. ファクトリービーン
「customer」BeanでdateFormat Beanを宣言し、「dateFormat」BeanをファクトリBeanとして参照します。 ファクトリメソッドはSimpleDateFormat.parse()
を呼び出して、StringをDateオブジェクトに自動的に変換します。
2. CustomDateEditor
Stringをjava.util.Dateに変換するCustomDateEditorクラスを宣言します。
また、別の「CustomEditorConfigurer」を宣言して、タイプがjava.util.DateのBeanプロパティをSpringに変換させます。
Bean構成ファイルの完全な例。
ソースコードをダウンロード
ダウンロード–Spring-CustomDateEditor-Example.zip(5KB)