我知道DateTimeFormat註釋可以在Spring中的Model類的Date屬性上定義,但是有什麼方法可以爲Spring Model類中的所有日期定義默認的dateTimeFormat註解嗎?在春天設置默認的DateTimeFormat註釋
@DateTimeFormat(圖案= 「MM/DD/YYYY」)
私人日期 deliveryDate;
這將使我無法註釋每個日期字段。這也將使我稍後可以輕鬆更改應用程序的寬日期格式。
我知道DateTimeFormat註釋可以在Spring中的Model類的Date屬性上定義,但是有什麼方法可以爲Spring Model類中的所有日期定義默認的dateTimeFormat註解嗎?在春天設置默認的DateTimeFormat註釋
@DateTimeFormat(圖案= 「MM/DD/YYYY」)
私人日期 deliveryDate;
這將使我無法註釋每個日期字段。這也將使我稍後可以輕鬆更改應用程序的寬日期格式。
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/YYYY");
binder.registerCustomEditor(Date.class, new CustomDateEditor(
dateFormat, false));
}
正如kuhajeyan提到的,你可以使用粘合劑,而不是在控制器上,而是基於控制器的建議,將全局應用:
@ControllerAdvice
public class GlobalDateBinder {
/* Initialize a global InitBinder for dates*/
@InitBinder
public void binder(WebDataBinder binder) {
// here you can use kuhajeyan's code
}
}
您可以創建一個自定義註釋有助於將日期解析爲默認格式。但是,您必須至少在日期屬性上添加自定義註釋 –