前端傳來的string在後臺接口中自動注入並轉換Date時如果報failed convert type of java.lang.String to required type of java.util.Date時,說明在注入屬性前初始化轉換這兩種類型沒做或者沒做好此時怎麼辦呢?
在接口中加一個在注入對象前的一個初始化即可很好用:
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import java.text.SimpleDateFormat;
import org.springframework.beans.propertyeditors.CustomDateEditor;
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}