AI智能
改变未来

基于spring boot实现空属性赋值和aspect日志


1. 空属性赋值问题

新增工具类
MyBeanUtils

package com.zr0726.news.util;import org.springframework.beans.BeanWrapper;import org.springframework.beans.BeanWrapperImpl;import java.beans.PropertyDescriptor;import java.util.ArrayList;import java.util.List;public class MyBeanUtils {public static String[] getNullPropertyName(Object source){BeanWrapper beanWrapper = new BeanWrapperImpl(source);PropertyDescriptor[] pds = beanWrapper.getPropertyDescriptors();List<String> nullPropertyName = new ArrayList<>();for (PropertyDescriptor pd:pds){String propertyName = pd.getName();if (beanWrapper.getPropertyValue(propertyName)==null){nullPropertyName.add(propertyName);}}return nullPropertyName.toArray(new String[nullPropertyName.size()] );}}

2.aspect日志

新建aspect包
LogAspect

package com.zr0726.news.aspect;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.*;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;import java.util.Arrays;@Aspect@Componentpublic class LogAspect {private final Logger logger = LoggerFactory.getLogger(this.getClass());@Pointcut(\"execution(* com.zr0726.news.web.*.*(..))\")public void log(){}@Before(\"log()\")public void doBefore(JoinPoint joinPoint){//获取requestServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();//获得url和ipString 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(\"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;}@Overridepublic String toString() {return \"RequestLog{\" +\"url=\'\" + url + \'\\\'\' +\", ip=\'\" + ip + \'\\\'\' +\", classMethod=\'\" + classMethod + \'\\\'\' +\", args=\" + Arrays.toString(args) +\'}\';}}}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » 基于spring boot实现空属性赋值和aspect日志