Spring Bean Utils复制属性枚举字段不起作用

时间:2017-07-13 20:59:17

标签: java reflection javabeans spring-bean

尝试将具有ENUM属性" valuetype"的源对象复制到目标对象中,其中" valuetype"是一个整数。但似乎它没有用。

来源



import com.ns.enums.DataType;

import lombok.Getter;

@Getter
public class UpdateConfigRequest {

    private String isenabled;

    private String value;

    private DataType valuetype;
}




:定位



import org.joda.time.DateTime;
import org.springframework.data.annotation.Id;
import org.springframework.data.cassandra.mapping.PrimaryKey;
import org.springframework.data.cassandra.mapping.Table;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Table("config")
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Config {

    @PrimaryKey
    @Id
    private String key;

    private DateTime created;

    private DateTime lastmodified;

    private boolean isenabled;

    private String value;

    private Integer valuetype;


}




* Bean Merge Class



import java.util.HashSet;
import java.util.Set;

import org.apache.commons.beanutils.PropertyUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.PropertyAccessorFactory;

public class BeanMerger {

	private static String[] getNullPropertyNames(Object source) {
		final BeanWrapper src = new BeanWrapperImpl(source);
		java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

		Set<String> emptyNames = new HashSet<String>();
		for (java.beans.PropertyDescriptor pd : pds) {
			Object srcValue = src.getPropertyValue(pd.getName());
			if (srcValue == null)
				emptyNames.add(pd.getName());
		}
		String[] result = new String[emptyNames.size()];
		System.out.println(result.length);
		return emptyNames.toArray(result);
	}

	public static Object merge(Object source, Object target) {
		BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
		if (propertyExists(source, "lastmodified")) {
			BeanWrapper trgWrap = PropertyAccessorFactory.forBeanPropertyAccess(source);
			trgWrap.setPropertyValue("lastmodified", new DateTime());
		}
		return source;
	}

	private static boolean propertyExists(Object bean, String property) {
		return PropertyUtils.isReadable(bean, property) && PropertyUtils.isWriteable(bean, property);
	}
	

}
&#13;
&#13;
&#13;

如上所述,我试图使用在Spring bean utils之上编写的BeanMerge.merge()包装器将UpdateConfigRequest类合并到Config。我看到一切正常,除了枚举值的副本。我怀疑从枚举到int的数据类型的更改导致了问题。无论如何要克服这个?

0 个答案:

没有答案