java注解类型的aop

import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
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;

@Aspect
@Component
public class FileLogAOP {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public FileLogAOP() {
    }

    @Pointcut("@annotation(com.wilmar.bms.commons.FileLogAnnotation)")
    public void controllerPointcut() {
    }

    @AfterReturning(
        pointcut = "controllerPointcut()",
        returning = "rel"
    )
    public void doAround(JoinPoint joinPoint, Object rel) {
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        String operatorName = ((UserDTO)request.getSession().getAttribute("user")).getName();
        ResultDTO resultDTO = (ResultDTO)rel;
        if("操作失败".equals(resultDTO.getMessage())) {
            String methodName = joinPoint.getSignature().getName();
            Method[] methods = joinPoint.getTarget().getClass().getMethods();
            Object[] args = joinPoint.getArgs();
            String functionName = null;
            Method[] arr$ = methods;
            int len$ = methods.length;

            for(int i$ = 0; i$ < len$; ++i$) {
                Method method = arr$[i$];
                if(method.getName().equals(methodName)) {
                    Class[] parameterTypes = method.getParameterTypes();
                    if(parameterTypes.length == args.length) {
                        FileLogAnnotation fileLog = (FileLogAnnotation)method.getAnnotation(FileLogAnnotation.class);
                        functionName = fileLog.remark();
                        break;
                    }
                }
            }

            this.logger.error("操作人:" + operatorName + "\t" + functionName + "\t" + resultDTO.getMessage());
        }

    }
}

  

posted @ 2019-03-27 09:27  growthofmonkey  阅读(417)  评论(0编辑  收藏  举报