AOP初体验

版权声明:转载请标明原作者及地址 https://blog.csdn.net/cauchy6317/article/details/82315281
package com.ax.ams.entity;


import com.ax.ams.configuration.MyInterceptor;
import com.ax.ams.service.DcBaseInfoLogService;
import com.ax.ams.toolClass.SomethingTypeEnum;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.Date;
import java.util.UUID;
import java.util.regex.Pattern;

@Aspect
@Component
public class CRUDAspect {

    private static final Logger logger = LoggerFactory.getLogger(CRUDAspect.class);

    @Autowired
    DcBaseInfoLogService  dcBaseInfoLogService;
    /**
     * 这样写是将重复的代码提取出来方便处理 execution(* com.xyz.service.AccountService.*(..))
     */

    @Pointcut("execution(* com.ax.ams.mapper.*.delete*(..))")
    public void log() {
    }


    @Before("log()")
    public void doBefore() {
//        logger.info("1");
//        logger.error("11");
    }

    /**
     *
     * @param joinPoint
     * 注意:该方法中的HttpServletRequest为javax.servlet.http.HttpServletRequest;
     */
    @After("log()")
    public void doAfter(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 记录请求路径url
        // logger.info("url={}",request.getRequestURL());

        // 记录请求方式method
        // logger.info("method={}",request.getMethod());

        // 记录访问者ip
        // logger.info("ip={}",request.getRemoteAddr());

        // 记录访问的类方法
        // logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());

        // 记录传递的参数
        // logger.info("args={}",joinPoint.getArgs());

    }

    @AfterReturning(returning = "obj",pointcut = "log()")
    public void doAfterReturning(JoinPoint joinPoint,Object obj) {
        // 获取HttpServletRequest对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

       // 实例化DcBaseInfoLog实体类对象dcBaseInfoLog
        DcBaseInfoLog dcBaseInfoLog = new DcBaseInfoLog();
        String uuid = UUID.randomUUID().toString();
        // 获取sessionInfo
        SessionInfo info = (SessionInfo)request.getSession().getAttribute(MyInterceptor.SESSION_KEY);
        // 操作结果默认为fail
        String result ="fail";
        // 根据访问的类的方法名判断操作类型,方法名中含“”“”“”“”“”"add"字段的,operationType为add,delete,update,select类推
        String operationType = "";
        // 后台增删改查的操作对象,根据增删改查所在mapper的类名决定,默认为“"未知对象"
        String somethingType ="未知对象";
        // 要验证的字符串,joinPoint.getSignature().getName()获取方法名
        String methodName = joinPoint.getSignature().getName();
        // 正则表达式规则
        String addRegEx = "add";
        String deleteRegEx = "delete";
        String updateRegEx = "update";
        String selectRegEx = "select";
        // 编译正则表达式, Pattern.CASE_INSENSITIVE 忽略大小写的写法
        Pattern addPattern = Pattern.compile(addRegEx, Pattern.CASE_INSENSITIVE);
        Pattern deletePattern = Pattern.compile(deleteRegEx, Pattern.CASE_INSENSITIVE);
        Pattern updatePattern = Pattern.compile(updateRegEx, Pattern.CASE_INSENSITIVE);
        Pattern selectPattern = Pattern.compile(selectRegEx, Pattern.CASE_INSENSITIVE);

        // 查找字符串中是否有匹配正则表达式的字符/字符串
        if(addPattern.matcher(methodName).find()){
            operationType = "add";
        }else if(deletePattern.matcher(methodName).find()){
            operationType = "delete";
        }else if(updatePattern.matcher(methodName).find()){
            operationType = "update";
        }else if(selectPattern.matcher(methodName).find()){
            operationType = "select";
        }
        // 根据增删改查所在mapper的类名mapperName,通过SomethingTypeEnum枚举类获取somethingType
        String mapperName = joinPoint.getSignature().getDeclaringTypeName();
        // mapperName先全转换成大写截取最后一个“”"."字符出现的位置后面的字符,如:com.ax.asm.mapper.DcSystemBaseRoleDao转换成DCSYSTEMBASEROLEDAO
        int lastDot = mapperName.lastIndexOf(".");
        mapperName = mapperName.toUpperCase().substring(lastDot+1);
        // 获取此时mapperName的枚举类实例,通过自定义的getSomethingType()方法获取somethingType,如DCSYSTEMBASEROLEDAO对应的somethingType为“"角色维护"
        somethingType = SomethingTypeEnum.valueOf(mapperName).getSomethingType();
        // 根据返回值确定结果
        if(Integer.parseInt(obj.toString()) > 0){
            result ="success";
        }

        dcBaseInfoLog.setId(uuid);
        dcBaseInfoLog.setIpAddress(request.getRemoteAddr());
        dcBaseInfoLog.setUserName(info.getAccount());
        dcBaseInfoLog.setUserId(info.getId());
        dcBaseInfoLog.setOperationType(operationType);
        //记录操作的具体类-->具体方法
        dcBaseInfoLog.setSomethingType(somethingType);
        dcBaseInfoLog.setRemark(joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
        dcBaseInfoLog.setResult(result);
        dcBaseInfoLog.setLevel("info");
        dcBaseInfoLog.setTime(new Date());
        dcBaseInfoLogService.addLoginLog(dcBaseInfoLog);
        logger.info("class_method={}",joinPoint.getSignature().getName());
    }

}

猜你喜欢

转载自blog.csdn.net/cauchy6317/article/details/82315281