我编写了一个update方法,它接受修改过的字段。
public ResponseEntity<String> updateProduct(@RequestBody final Product product)
{
returnValue = productService.updateProduct(product);
}产品是一个bean类,拥有50个属性列表。从UI中,如果我修改5个字段,它将这些修改后的字段和其他属性保存为null。如何在这里进行过滤?我只想传递更新的值。
returnValue = productService.updateProduct(product); 发布于 2016-05-24 07:47:01
很难不看到来自Product类或ProductService.updateProduct方法的任何代码。但是,您可以使用Apache中提供的BeanUtilsBean类。
public static void nullAwareBeanCopy(Object dest, Object source) throws IllegalAccessException, InvocationTargetException {
new BeanUtilsBean() {
@Override
public void copyProperty(Object dest, String name, Object value)
throws IllegalAccessException, InvocationTargetException {
if(value != null) {
super.copyProperty(dest, name, value);
}
}
}.copyProperties(dest, source);
}这是我编写的一篇文章,但是由于您使用了spring,您可能希望使用位于org.springframework.beans.BeanUtils的spring类。在快速搜索代码时,我遇到了this answer from alfredx,它有以下代码
public 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()];
return emptyNames.toArray(result);
}
// then use Spring BeanUtils to copy and ignore null
public static void myCopyProperties(Object, src, Object target) {
BeanUtils.copyProperties(src, target, getNullPropertyNames(src))
}然后,您可以像这样使用它:
public void updateProduct(Product updatedProduct) {
Product existingProduct = /*find existing product*/;
nullAwareBeanCopy(existingProduct, updatedProduct);
// or
myCopyProperties(updatedProduct, existingProduct);
}监视这两种不同的方法源/目标参数是完全相反的。
https://stackoverflow.com/questions/37407000
复制相似问题