空属性赋值问题+aspect日志

在更新新闻对象的时候,我们是将一个new对象赋值到目标对象中,但是其中的属性值有可能为null,而原对象当中是存在的,被null覆盖掉了,所以需要对空属性进行赋值问题的解决。
1.考虑到copy是在beanutils内,这里创建mybeanutils对空值打包提取出来

public class MyBeanUtils {
public static String[] getNullPropertyNames(Object source){
BeanWrapper beanWrapper = new BeanWrapperImpl(source);
PropertyDescriptor[] pds = beanWrapper.getPropertyDescriptors();
List nullPropertyNames = new ArrayList<>();
for(PropertyDescriptor pd:pds){
String propertyName = pd.getName();
if(beanWrapper.getPropertyValue(propertyName)==null){
nullPropertyNames.add(propertyName);
}
}
return nullPropertyNames.toArray(new String[nullPropertyNames.size()]);
}
}

@Override
public News updateNew(Long id, News news) {
News news1 = newRepository.findById(id).orElse(null);
if(news1==null){
// System.out.println(“未获得更新对象”);
throw new NotFoundException(“该新闻不存在”);
}
BeanUtils.copyProperties(news,news1, MyBeanUtils.getNullPropertyNames(news));
news1.setUpdateTime(new Date());
return newRepository.save(news1);
}

日志导入
@Aspect
@Component
public class LogAspect {

private final Logger logger = LoggerFactory.getLogger(this.getClass());

@Pointcut("execution(* com.lin.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.getRequestURI().toString(); //不打印localhost:8080
String url =request.getRequestURL().toString(); //打印localhost:8080
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;

    public RequestLog(String url, String ip, String classMethod, Object[] args) {
        this.url = url;
        this.ip = ip;
        this.classMethod = classMethod;
        this.args = args;
    }

    @Override
    public String toString() {
        return "RequestLog{" +
                "url='" + url + '\'' +
                ", ip='" + ip + '\'' +
                ", classMethod='" + classMethod + '\'' +
                ", args=" + Arrays.toString(args) +
                '}';
    }
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值