空属性赋值问题与aop实现日志

空属性赋值问题

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()
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值