在一次偶然的机会,写出了一个“屎山”代码,秉着严谨的态度(看着实在不舒服),尝试了一下优化,并用博客记录一波
1. 优化前
@PostMapping("/confirmUserAddress")
public Map<String,Object> confirmUserAddress(
boolean checked,
String city,
String detail,
String district,
String iphone,
String province,
String realName
){
Map<String,Object> map = new HashMap<>(6);
UserAddress userAddress = new UserAddress();
userAddress.setUid(LocalUser.getUser().getUid());
userAddress.setRealName(realName);
userAddress.setPhone(iphone);
userAddress.setProvince(province);
userAddress.setCity(city);
userAddress.setDistrict(district);
userAddress.setDetail(detail);
userAddress.setIsDefault(checked==true?1:0);
userAddress.setIsDel(0);
userAddress.setCreateTime(new Date());
......
return map;
}
2. 优化后
@PostMapping("/confirmUserAddress")
public Map<String,Object> confirmUserAddress(@RequestBody UserAddressParam userAddressParam){
Map<String,Object> map = new HashMap<>(6);
UserAddress userAddress = new UserAddress();
if(!ObjectUtils.isEmpty(userAddressParam)) {
BeanUtils.copyProperties(userAddressParam,userAddress);
}
userAddress.setUid(LocalUser.getUser().getUid());
......
return map;
}
3. 优化方案<BeanUtils.copyProperties>
package org.springframework.beans;
.......
/**
注解为:spring源码英文注解翻译后结果
将给定源 bean 的属性值复制到目标 bean 中。
注意:只要属性匹配,源类和目标类不必匹配,甚至可以从彼此派生。 源 bean 公开但目标 bean 没有公开的任何 bean 属性都将被静默忽略。
这只是一种方便的方法。 对于更复杂的传输需求,请考虑使用完整的 BeanWrapper。
参数:
source – 源 bean
target – 目标 bean
抛出:
BeansException – 如果复制失败
**/
public static void copyProperties(Object source, Object target) throws BeansException {
copyProperties(source, target, null, (String[]) null);
}
/**
* @param editable the class (or interface) to restrict property setting
* 将属性设置限制为的类(或接口)
**/
public static void copyProperties(Object source, Object target, Class<?> editable) throws BeansException {
copyProperties(source, target, editable, (String[]) null);
}
如果在copy对象的过程中需要忽略某个实体类属性,可以调用下列方法:
package org.springframework.beans;
/**
将给定源 bean 的属性值复制到给定目标 bean 中,忽略给定的“ignoreProperties”。
注意:只要属性匹配,源类和目标类不必匹配,甚至可以从彼此派生。 源 bean 公开但目标 bean 没有公开的任何 bean 属性都将被静默忽略。
这只是一种方便的方法。 对于更复杂的传输需求,请考虑使用完整的 BeanWrapper
**/
.......
public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException {
copyProperties(source, target, null, ignoreProperties);
}
4. 后言
拒绝屎山代码~
本文分享了一次从冗长‘屎山’代码到使用Spring BeanUtils进行对象映射优化的过程,展示了如何通过注解减少重复,提升代码可读性。
790

被折叠的 条评论
为什么被折叠?



