Dozer 自定义Converter -- LocalDateTime to Date

Spring boot项目,使用dozer将Jpa Entity中的LocalDateTime属性转到DTO中对应的LocalDateTime属性中报错

java.lang.NoSuchMethodException: java.time.LocalDateTime.<init>()
	at java.lang.Class.getConstructor0(Class.java:3082) ~[na:1.8.0_51]
	at java.lang.Class.getDeclaredConstructor(Class.java:2178) ~[na:1.8.0_51]
	at org.dozer.factory.ConstructionStrategies$ByConstructor.newInstance(ConstructionStrategies.java:272) ~[dozer-5.5.1.jar:na]

将DTO中的LocalDateTime换成Date又报错

java.lang.NumberFormatException: For input string: "2015-10-17T17:55:12.091"

解决方法:

添加一个自定义Convert

public class LocalDateTimeToDateDozerConverter extends DozerConverter<LocalDateTime, Date> {

  public LocalDateTimeToDateDozerConverter() {
    super(LocalDateTime.class, Date.class);
  }

  @Override
  public LocalDateTime convertFrom(Date source, LocalDateTime destination) {
    LocalDateTime dateTime = LocalDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault());
    return dateTime;
  }

  @Override
  public Date convertTo(LocalDateTime source, Date destination) {
    Date convertToDate = Date.from(source.atZone(ZoneId.systemDefault()).toInstant());
    return convertToDate;
  }

}

在类路径下添加一个xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://dozer.sourceforge.net
          http://dozer.sourceforge.net/schema/beanmapping.xsd">
  <configuration>
    <custom-converters> <!-- these are always bi-directional -->
      <converter type="com.demo.LocalDateTimeToDateDozerConverter" >
        <class-a>java.time.LocalDateTime</class-a>
        <class-b>java.util.Date</class-b>
      </converter>
    </custom-converters>     
  </configuration>
  
</mappings>

注意像这样的全局配置只能使用xml的形式配置,见官方文档

In fact some parts of the configuration (e.g. global configuration block) are only possible to express in Xml format.

Spring boot启动类中添加如下配置

 @Bean
  public Mapper dozerBeanMapper() {
    List<String> mappingFileUrls = Lists.newArrayList("dozer-custom-convert.xml");
    DozerBeanMapper mapper = getSingletonDozerBeanMapper();
    mapper.setMappingFiles(mappingFileUrls);
    return mapper;
  }

参考文档

http://dozer.sourceforge.net/documentation/customconverter.html

http://stackoverflow.com/questions/29550417/why-dozerconverter-is-not-working

时间: 2024-08-08 04:02:24

Dozer 自定义Converter -- LocalDateTime to Date的相关文章

Java日期时间API系列13-----Jdk8中java.time包中的新的日期时间API类,时间类转换,Date转LocalDateTime,LocalDateTime转Date

从前面的系列博客中可以看出Jdk8中java.time包中的新的日期时间API类设计的很好,但Date由于使用仍非常广泛,这就涉及到Date转LocalDateTime,LocalDateTime转Date.下面是时间类互相转换大全,包含Instant.LocalDate.LocalDateTime.LocalTime和Date的相互转换,下面是一个工具类,仅供参考: package com.xkzhangsan.time.converter; import java.time.Instant;

Retrofit 2 0 自定义Converter

requestBodyConverter 不执行的解决办法: 参数要使用@Body这种形式,否则 request 方法会不起作用. 在Retrofit中,无论是发送数据和接收数据,都是通过OKHttp的RequestBody和ResponseBody来实现的.在实际项目中,有时候原始的RequestBody或是ResponseBody并不能满足我们的需求(如接口加密),就需要对它进行转换. 在Retrofit通过build()方法获得实例时,可以添加多个ConverterFactory,但要注意

System.Text.Json 自定义Converter实现时间转换

Newtonsoft.Json与System.Text.Json区别 在 Newtonsoft.Json中可以使用例如 .AddJsonOptions(options => { options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; }) 方式设置接收/序列化时间格式,但在.net core 3.1中System.Text.Json是没有自带方式进行转换,这就需要自定义Converter实现时间转换

springMVC自定义类型转换器(date类型转换)

//日期的月份不能写成小写mm,因为在日期中还有分钟mm,这两者不能相同. 1.创建一个类实现Convert接口,实现convert方法 public date convert(String source){ if(source!=null&&!source.equals(""){ SimpleDateFormat sdf=getSimpleDateFormat(source); return sdf.parse(source); } } public Date get

java日期互转:LocalDateTime、String、TimeStamp、Long、Instant、Date

由于java版本的迭代,一个使用java开发的项目中可能出现多种日期对象,例如LocalDateTime.LocalDate.Date,不像C#只有一个DateTime,因此在各种日期格式或者对象之间的转换显得有点复杂,总是记不住,在需要用到时总是需要依靠搜索引擎,有点浪费时间,所以特意把常用的转换场景总结如下: 1. LocalDateTime转为String.TimeStamp.Long.Instant. Date System.out.println("----------------Lo

spring自定义参数绑定(日期格式转换)

spring参数绑定时可能出现 BindException(参数绑定异常),类似下面的日期绑定异常(前台传过来是String类型,实际的pojo是Date类型) default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'endTime'; nested exception is org.springfram

springmvc Converter

以下,来自于Springmvc指南第二版,第93页. Spring的Converter是可以将一种类型转为另一种类型. 例如用户输入的date类型可能有多种格式. 比如:在controller中接收一个LocalDate. @RequestMapping(value = "/test",produces = "text/html;charset=UTF-8") @ResponseBody public String test(@RequestParam(requir

Java 8 新特性:Java 类库的新特性之日期时间API (Date/Time API ) ——诺诺&quot;涂鸦&quot;记忆

----------   诺诺学习技术交流博客.期待与您交流!    ---------- 详情请查看:http://blog.csdn.net/sun_promise  日期时间API (Date/Time API ) 1.Java8之前java.util.Date和Calendar类的弊端 1)最开始的时候,Date既要承载日期信息,又要做日期之间的转换,还要做不同日期格式的显示,职责较繁杂(不遵守单一职责). 后来从JDK 1.1 开始,这三项职责分开了: 使用Calendar类实现日期和

权限框架 - shiro 自定义realm

上篇文章中是使用的默认realm来实现的简单登录,这仅仅只是个demo,真正项目中使用肯定是需要连接数据库的 首先创建自定义realm文件,如下: 在shiro中注入自定义realm的完全限定类名: 1 [main] 2 # your custom realm path 3 fooRealm=com.lee.shiro.realm.FooRealm 4 # DI such as spring DI 5 securityManager.realms=$fooRealm 自定义realm认证: 1