空属性赋值问题
BeanUtils.copyProperties(Object source, Object target)方法可以快速的将source对象中的属性赋值给target对象。当我们对java实体执行相关操作时,使用BeanUtils工具可以快速执行新增、修改时对实体属性的赋值操作。
但是若source对象中的属性为null时,target中相应的属性也会被修改为null,有时候这可能不是我们希望的结果。
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);
}
//调用上述方法:
BeanUtils.copyProperties(source, target, BeanOperateUtil.gainNullPropertyNames(source));
aop实现日志
AOP是Spring框架面向切面的编程思想,AOP采用一种称为“横切”的技术,将涉及多业务流程的通用功能抽取并单独封装,形成独立的切面,在合适的时机将这些切面横向切入到业务流程指定的位置中。
@Aspect
@Component
public class LogAspect {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Pointcut("execution(* com.by.news.web.*.*(..))")
public void log(){
}
@Before("log()")
public void deBefore(JoinPoint joinPoint){
//获取request
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request =attributes.getRequest();
//获得url和ip
String url =request.getRequestURL().toString();
String ip = request.getRemoteAddr();
String classMethod =joinPoint.getSignature().getDeclaringTypeName()+".";
Object[] args = joinPoint.getArgs();
RequestLog requestLog = new RequestLog(url,ip,classMethod,args);
logger.info("Request:{}",requestLog);
logger.info("-------doBefore-------");
}
@After("log()")
public void doAfter(){
logger.info("-------doAfter-------");
}
@AfterReturning(returning = "result",pointcut = "log()")
public void adAfterReturn(Object result){
logger.info("result:{}"+result);
}
private class RequestLog{
private String url;
private String ip;
private String classMethod;
private Object[] args;
//constructor&toString()
}
}