feat: 增加一个BeanUtils

This commit is contained in:
zengxiaobo 2024-05-31 16:30:46 +08:00
parent 92aa002a00
commit eee28c81bc

View File

@ -0,0 +1,69 @@
package cn.axzo.foundation.web.support.utils;
import com.google.common.collect.Sets;
import org.springframework.cglib.beans.BeanMap;
import java.util.*;
import java.util.stream.Collectors;
public class AxBeanUtils extends org.springframework.beans.BeanUtils {
/**
* 在拷贝属性时忽略空值, 并且可以指定忽略其他的属性
*
* @param src
* @param target
*/
public static void copyPropertiesIgnoreNull(Object src, Object target, String... ignoreProperties) {
Set<String> ignoreNullProperties = ((Map<String, Object>) BeanMap.create(src))
.entrySet().stream().filter(f -> Objects.isNull(f.getValue()))
.map(Map.Entry::getKey).collect(Collectors.toSet());
if (ignoreProperties != null && ignoreProperties.length > 0) {
ignoreNullProperties.addAll(Arrays.asList(ignoreProperties));
}
copyProperties(src, target, ignoreNullProperties.toArray(new String[]{}));
}
/**
* 在拷贝属性时忽略空值
*
* @param src
* @param target
*/
public static void copyPropertiesIgnoreNull(Object src, Object target) {
copyPropertiesIgnoreNull(src, target, new String[]{});
}
/**
* 拷贝对象支持feature控制拷贝逻辑
*
* @param src
* @param target
* @param features
*/
public static void copyProperties(Object src, Object target, Feature... features) {
Set<Feature> featureSet = Optional.ofNullable(features).map(Sets::newHashSet).orElse(Sets.newHashSet());
Set<String> ignoreProperties = Sets.newHashSet();
if (featureSet.contains(Feature.IGNORE_SRC_NULL)) {
ignoreProperties.addAll(((Map<String, Object>) BeanMap.create(src)).entrySet().stream().filter(f -> Objects.isNull(f.getValue()))
.map(Map.Entry::getKey).collect(Collectors.toSet()));
}
if (featureSet.contains(Feature.DISALLOW_OVERWRITE_TARGET)) {
ignoreProperties.addAll(((Map<String, Object>) BeanMap.create(target))
.entrySet().stream().filter(f -> f.getValue() != null)
.map(Map.Entry::getKey).collect(Collectors.toSet()));
}
copyProperties(src, target, ignoreProperties.toArray(new String[]{}));
}
public enum Feature {
// 源对象的属性为空的不拷贝
IGNORE_SRC_NULL,
// 目标对象的属性不为空的不拷贝
DISALLOW_OVERWRITE_TARGET
}
}