BeanUtils.copyProperties支持Date类型

本文介绍了一个扩展的BeanUtils类,该类增加了对日期类型的转换支持,通过自定义的日期转换器,使得Bean属性复制时能更好地处理日期格式。
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.log4j.Logger;

/**
 * @Title 扩展BeanUtils.copyProperties支持data类型
 * @Description
 * @author wangzs
 * @date 2017-1-5
 */
public class BeanUtilsEx extends BeanUtils {
	private static Logger logger = Logger.getLogger(BeanUtilsEx.class);

	static {
		ConvertUtils.register(new DateConvert(), java.util.Date.class);
		ConvertUtils.register(new DateConvert(), String.class);
	}

	public static void copyProperties(Object target, Object source) {
		// 支持对日期copy
		try {
			org.apache.commons.beanutils.BeanUtils.copyProperties(target, source);
		} catch (IllegalAccessException | InvocationTargetException e) {
			logger.error("扩展BeanUtils.copyProperties支持data类型:" + e.getMessage());
			e.printStackTrace();
		}
	}
}


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.beanutils.Converter;

/**
 * @Title 扩展BeanUtils.copyProperties支持data类型
 * @Description
 * @author wangzs
 * @date 2017-1-5
 */
public class DateConvert implements Converter {
	@Override
	public Object convert(Class class1, Object value) {
		if (value == null) {
			return null;
		}
		if (value instanceof Date) {
			return value;
		}
		if (value instanceof Long) {
			Long longValue = (Long) value;
			return new Date(longValue.longValue());
		}
		if (value instanceof String) {
			String dateStr = (String) value;
			Date endTime = null;
			try {
				String regexp1 = "([0-9]{4})-([0-1][0-9])-([0-3][0-9])T([0-2][0-9]):([0-6][0-9]):([0-6][0-9])";
				String regexp2 = "([0-9]{4})-([0-1][0-9])-([0-3][0-9])(/t)([0-2][0-9]):([0-6][0-9]):([0-6][0-9])";
				String regexp3 = "([0-9]{4})-([0-1][0-9])-([0-3][0-9])";
				if (dateStr.matches(regexp1)) {
					dateStr = dateStr.split("T")[0] + " " + dateStr.split("T")[1];
					DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					endTime = sdf.parse(dateStr);
					return endTime;
				} else if (dateStr.matches(regexp2)) {
					DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					endTime = sdf.parse(dateStr);
					return endTime;
				} else if (dateStr.matches(regexp3)) {
					DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					endTime = sdf.parse(dateStr);
					return endTime;
				} else {
					return dateStr;
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return value;
	}
}


在Spring Boot中使用`BeanUtils.copyProperties(reqBody, entity)`方法时,Date类型报错通常是由于源对象和目标对象的Date类型字段在格式或类型上不匹配。以下是几种常见的解决方法: ### 自定义属性转换器 可以通过实现`Converter`接口来自定义属性转换器,将源对象的Date类型字段转换为目标对象可接受的Date格式。示例代码如下: ```java import org.springframework.core.convert.converter.Converter; import java.util.Date; public class CustomDateConverter implements Converter<String, Date> { @Override public Date convert(String source) { // 这里根据实际情况实现日期字符串到Date的转换 // 例如使用SimpleDateFormat try { java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd"); return sdf.parse(source); } catch (Exception e) { return null; } } } ``` 然后在配置类中注册这个转换器。 ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.support.ConfigurableConversionService; import org.springframework.core.convert.support.DefaultConversionService; @Configuration public class ConversionConfig { @Bean public ConfigurableConversionService conversionService() { DefaultConversionService conversionService = new DefaultConversionService(); conversionService.addConverter(new CustomDateConverter()); return conversionService; } } ``` ### 手动处理Date类型字段 在调用`BeanUtils.copyProperties`方法之后,手动处理Date类型的字段。示例代码如下: ```java import org.springframework.beans.BeanUtils; public class Main { public static void main(String[] args) { SourceObject reqBody = new SourceObject(); TargetObject entity = new TargetObject(); // 先复制其他属性 BeanUtils.copyProperties(reqBody, entity); // 手动处理Date类型字段 if (reqBody.getDate() != null) { entity.setDate(reqBody.getDate()); } } } class SourceObject { private java.util.Date date; public java.util.Date getDate() { return date; } public void setDate(java.util.Date date) { this.date = date; } } class TargetObject { private java.util.Date date; public java.util.Date getDate() { return date; } public void setDate(java.util.Date date) { this.date = date; } } ``` ### 使用其他对象复制工具 除了Spring的`BeanUtils`,还可以使用其他对象复制工具,如Apache Commons BeanUtils或Dozer。以Apache Commons BeanUtils为例,示例代码如下: ```java import org.apache.commons.beanutils.BeanUtils; public class Main { public static void main(String[] args) throws Exception { SourceObject reqBody = new SourceObject(); TargetObject entity = new TargetObject(); // 使用Apache Commons BeanUtils复制属性 BeanUtils.copyProperties(entity, reqBody); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值