我编写了一个更新方法,它接受修改的字段。
public ResponseEntity<String> updateProduct(@RequestBody final Product product)
{
returnValue = productService.updateProduct(product);
}
Product是一个bean类,拥有50个属性列表。从 UI 中,如果我修改 5 个字段,它会将这些修改的字段和其他属性保留为 null。这里如何进行过滤呢?我只想传递更新后的值
returnValue = productService.updateProduct(product);
最佳答案
如果没有看到 Product
类或 ProductService.updateProduct
方法中的任何代码,就很难说。不过,您也许可以使用 Apache Commons 库中提供的 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 bean utils 类。快速搜索该代码时我发现了 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);
}
注意这两种不同的方法源/目标参数彼此相反。
关于Java:如何忽略具有 null 的字段并仅通过修改后的属性传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37407000/