這篇文章帶給大家的內容是關於spring boot如何配置全域日期類型轉換器(程式碼) ,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。
1. 首先自訂一個類型轉換器
import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; @Component public class MyDataConvert implements Converter<String, Date> { //这里可以自己灵活变通 private String [] pattern = {"yyyy-MM-dd","yyyy年MM月dd日"}; @Override public Date convert(String s) { System.out.println("convert"); for (int i=0;i<pattern.length;i++){ try { return new SimpleDateFormat(pattern[i]).parse(s); } catch (ParseException e) { continue; } } return null; } }
2.在設定類別中註冊自訂類型轉換器
import com.example.demo.convert.MyDataConvert; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; import javax.annotation.PostConstruct; @Configuration public class WebConfigurer extends WebMvcConfigurationSupport { @Autowired private RequestMappingHandlerAdapter handlerAdapter; @PostConstruct public void initEditableAvlidation() { ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer)handlerAdapter.getWebBindingInitializer(); if(initializer.getConversionService()!=null) { GenericConversionService genericConversionService = (GenericConversionService)initializer.getConversionService(); genericConversionService.addConverter(new MyDataConvert());//添加自定义的类型转换器 } } }
相關推薦:
mysql 查詢int類型日期轉換成datetime類型
##
以上是spring boot如何配置全域日期類型轉換器(程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!