Весенний пример, показывающий, как ввести “Дату” в свойство компонента.
package com.mkyong.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 + "]"; } }
Файл конфигурации компонента
Запустите его
package com.mkyong.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
Решение
Весной вы можете ввести дату двумя способами:
1. Заводской завод
Объявите формат даты в компоненте “клиент”, ссылающемся на компонент “Формат даты” как на заводской компонент. Заводской метод вызовет SimpleDateFormat.parse()
для автоматического преобразования строки в объект даты.
2. Пользовательская дата
Объявляет класс CustomDateEditor для преобразования строки в java.util. Дата .
И объявляет другой “customeditorconfigurer”, чтобы заставить Spring конвертировать свойства компонента, тип которого java.util. Дата .
Полный пример файла конфигурации компонента.
Скачать Исходный Код
Ссылка
Оригинал: “https://mkyong.com/spring/spring-how-to-pass-a-date-into-bean-property-customdateeditor/”