spring boot空属性赋值问题与aspect日志实现方法

网友投稿 284 2022-11-28


spring boot空属性赋值问题与aspect日志实现方法

空属性赋值问题

MyBeanUtils类

public class MyBeanUtils {

public static String[] getNullPropertyNames(Object source){

BeanWrapper beanWrapper=new BeanWrapperImpl(source);

PropertyDescriptor[] pds=beanWrapper.getProperthttp://yDescriptors();

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()]);

}

}

在NewServiceImpl中对updateNew方法进行修改

@Override

public News updateNew(Long id, News news) {

News news1=newRepository.findById(id).orElse(null);

if(news1==null){

// System.out.println("未获得更新对象");

throw new NotFoundException("该新闻不存在");

}

//更新后传入的news复制给news1,查找更新数据news中空值属性,忽略不复制给news1

BeanUtils.copyProperties(news,news1, MyBeanUtils.getNullPropertyNames(news));

news1.setUpdateTime(new Date());

return newRepository.save(news1);

}

日志打印

新建一个LogAspect类

@Aspect

@Component

public class LogAspect {

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

@Pointcut("execution(* com.zr0726.news.web.*.*(..))")

public void log(){}

@Before("loghttp://()")

public void doBefore(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()+"."+joinPoint.getSignature().getName();

Object[] args=joinPoint.getArgs();

Requestlog requestlog=new Requestlog(url,ip,classMethod,args);

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 className, Object[] args) {

this.url = url;

this.ip = ip;

this.classMethod = className;

this.args = args;

}

@Override

public String toString() {

return "Requestlog{" +

"url='" + url + '\'' +

", ip='" + ip + '\'' +

", classMethod='" + classMethod + '\'' +

", args=" + Arrays.toString(args) +

'}';

}

}

}

效果展示

总结


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:MyBatis 三表外关联查询的实现(用户、角色、权限)
下一篇:Win10 Java jdk14.0.2安装及环境变量配置详细教程
相关文章

 发表评论

暂时没有评论,来抢沙发吧~