aop

aop

是干嘛的?

spring提供的一种机制在一个方法前后执行相应的动作,比如日志,或者是版本迭代升级对主体内容无需过多的修改

在进行aop编程前,我们先准备一下

spring依赖

aop处理类

    package spring_aop.component;
    
    import cn.hutool.core.util.StrUtil;
    import cn.hutool.core.util.URLUtil;
    import cn.hutool.json.JSONUtil;
    import com.alibaba.druid.util.StringUtils;
    import io.swagger.annotations.ApiOperation;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.Signature;
    import org.aspectj.lang.annotation.*;
    import org.aspectj.lang.reflect.MethodSignature;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.core.annotation.Order;
    import org.springframework.stereotype.Component;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    import spring_aop.dto.WebLog;
    
    
    import javax.servlet.http.HttpServletRequest;
    import java.lang.reflect.Method;
    import java.lang.reflect.Parameter;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    /**
     * 统一日志处理界面
     */
    @Aspect
    @Component
    @Order(1)
    public class WebLogAspect {
        private static final Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);
    
        /**
         * 切入点
         */
        @Pointcut("execution(public * spring_aop.controller.*.*(..))")
        public void weblog(){}
    	
    	//执行方法前
        @Before("weblog()")
        public void dobefore(JoinPoint joinPoint){
    
        }
        //结果返回前
        @AfterReturning(value = "weblog()", returning = "ret")
        public void doAfterReturning(Object ret) throws Throwable {
        }
        //方法执行前后
        @Around("weblog()")
        public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
            long starttime = System.currentTimeMillis();
            //获取当前对象
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request =attributes.getRequest();
            //记录请求信息
            WebLog webLog = new WebLog();
            Object result = joinPoint.proceed();
            Signature signature = joinPoint.getSignature();
            MethodSignature methodSignature = (MethodSignature) signature;
            Method method = methodSignature.getMethod();
            if (method.isAnnotationPresent(ApiOperation.class)) {
                ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
                webLog.setDescription(apiOperation.value());
            }
            long endTime = System.currentTimeMillis();
            String urlStr = request.getRequestURL().toString();
            webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
            webLog.setIp(request.getRemoteUser());
            webLog.setMethod(request.getMethod());
            webLog.setParameter(getParameter(method, joinPoint.getArgs()));
            webLog.setResult(result);
            webLog.setSpendTime((int) (endTime - starttime));
            webLog.setStartTime(starttime);
            webLog.setUri(request.getRequestURI());
            webLog.setUrl(request.getRequestURL().toString());
            LOGGER.info("{}", JSONUtil.parse(webLog));
            return result;
        }
    
        /**
         * 根据方法和传入的参数获取请求参数
         */
        private Object getParameter(Method method, Object[] args) {
            List<Object> argList = new ArrayList<>();
            Parameter[] parameters = method.getParameters();
            for (int i = 0; i < parameters.length; i++) {
                //将RequestBody注解修饰的参数作为请求参数
                RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
                if (requestBody != null) {
                    argList.add(args[i]);
                }
                //将RequestParam注解修饰的参数作为请求参数
                RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
                if (requestParam != null) {
                    Map<String, Object> map = new HashMap<>();
                    String key = parameters[i].getName();
                    if (!StringUtils.isEmpty(requestParam.value())) {
                        key = requestParam.value();
                    }
                    map.put(key, args[i]);
                    argList.add(map);
                }
            }
            if (argList.size() == 0) {
                return null;
            } else if (argList.size() == 1) {
                return argList.get(0);
            } else {
                return argList;
            }
        }
    }
    

原文地址:https://www.cnblogs.com/xiaozhazhahui/p/15077170.html