AOP使用案例

AOP使用案例

1、编写一个切面注解

import java.lang.annotation.*;

/**
 * @author HARRIS
 * 操作记录日志注解
 */
@Target({
    
    ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperationRecordAspect {
    
    

    String description() default "";

}

2、编写切面类

import com.alibaba.dubbo.config.annotation.Reference;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
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.lang.reflect.Method;
import java.util.Date;
import java.util.List;

/**
 * 操作记录日志切面类
 */
@Aspect
@Component
public class OperationRecordLogAspect {
    
    

    private Logger logger = LoggerFactory.getLogger(OperationRecordLogAspect.class);

    @Autowired(required = false)
    private SnowFlakeIdWorker snowFlakeIdWorker;

    @Autowired
    private OperationRecordLogService operationRecordLogService;
    
    @Pointcut("@annotation(com.*.OperationRecordAspect)")
    public void accessOperationRecordLogAspect() {
    
    

    }

    @Around("accessOperationRecordLogAspect()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    
    
        Object object = new Object();

        logger.info("***********操作记录日志开始记录*******");

		// 接收到请求,记录请求内容
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        OperationRecordLog operationRecordLog = new OperationRecordLog();
        operationRecordLog.setId(snowFlakeIdWorker.nextId());
        operationRecordLog.setOperationTime(new Date());
        String ip = IpUtils.getRequestIp(request);
        if (StringUtils.isBlank(ip)) {
    
    
            ip = IpUtils.getInnerIp();
        }
        operationRecordLog.setOperationIp(ip);
        //从作用域中取值即可,方法接收的参数值都可以取到
        String loginUserId = request.getParameter("loginUserId");
        if (StringUtils.isBlank(loginUserId)) {
    
    
            loginUserId = LoginUserUtil.getLoginId();
        }
        if (StringUtils.isNotBlank(loginUserId)) {
    
    
            operationRecordLog.setUserId(loginUserId);
            List<Organization> organizationList = organizationService.getOrgListByUser(loginUserId);
            if (CollectionUtil.isNotEmpty(organizationList)) {
    
    
                operationRecordLog.setDepartmentId(organizationList.get(0).getId());
                operationRecordLog.setDepartmentName(organizationList.get(0).getName());
            }
        }
        String loginName = request.getParameter("loginName");
        if (StringUtils.isBlank(loginName) && StringUtils.isNotBlank(loginUserId)) {
    
    
            User byId = userService.getById(loginUserId);
            if (null != byId) {
    
    
                loginName = byId.getRealName();
                if (com.greatmap.gaism.util.StringUtil.isBlank(loginName)) {
    
    
                    loginName = LoginUserUtil.getLoginName();
                }
            }else{
    
    
                if (com.greatmap.gaism.util.StringUtil.isBlank(loginName)) {
    
    
                    loginName = LoginUserUtil.getLoginName();
                }
            }
        }
        if (StringUtils.isNotBlank(loginName)) {
    
    
            operationRecordLog.setUserName(loginName);
            operationRecordLog.setUserCreate(loginName);
        }
        Class<?> clazz = joinPoint.getTarget().getClass();
        if (clazz.isAnnotationPresent(OperationRecordAspect.class)) {
    
    
            operationRecordLog.setOperationRecord(clazz.getAnnotation(OperationRecordAspect.class).description());
        }
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method targetMethod = methodSignature.getMethod();
        if (targetMethod.isAnnotationPresent(OperationRecordAspect.class)) {
    
    
            operationRecordLog.setOperationRecord(
                    (StringUtils.isNotBlank(operationRecordLog.getOperationRecord()) ? operationRecordLog.getOperationRecord() + "--" : "") +
                            targetMethod.getAnnotation(OperationRecordAspect.class).description());
        }
        if (StringUtils.isNotBlank(request.getParameter("note"))) {
    
    
            operationRecordLog.setNote(request.getParameter("note"));
        }
        operationRecordLog.setDelFlag(1);
        operationRecordLog.setVersion(0);
        operationRecordLog.setGmtCreate(new Date());
        operationRecordLogService.insert(operationRecordLog);
        logger.info("***********操作记录日志保存成功*******");
        try {
    
    
            object = joinPoint.proceed();
        } catch (Throwable throwable) {
    
    
            throwable.printStackTrace();
            logger.error(String.format("操作记录日志切面请求失败!失败原因为:%s", throwable.getMessage()));
            throw throwable;
        }
        return object;
    }

}

3、使用切面

	@ApiOperation("编辑电子责任书")
    @PostMapping("editElectronicResponsibility")
    @OperationRecordAspect(description = "编辑电子责任书")
    public RestResult editElectronicResponsibility(@ApiParam(value = "当前登录用户id") @RequestParam(value = "loginUserId", required = true) String loginUserId,
                                                   @ApiParam(value = "用户姓名") @RequestParam(value = "loginName", required = true) String user_name,
                                                   @ApiParam(value = "部门id") @RequestParam(value = "orgId", required = true) String org_id,
                                                   @ApiParam(value = "部门名称") @RequestParam(value = "orgName", required = true) String org_name,
                                                   @ApiParam(value = "电子责任书id") @RequestParam(value = "id", required = true) String id,
                                                   @ApiParam(value = "标题") @RequestParam(value = "title", required = true) String title,
                                                   @ApiParam(value = "曝光文档地址") @RequestParam(value = "contentUrl", required = false) String contentUrl,
                                                   @ApiParam(value = "案例内容") @RequestBody(required = false) String content,
                                                   @ApiParam(value = "备注 eg:编辑") @RequestParam(value = "note", required = true) String comment) {
    
    
        if (StringUtils.isBlank(id)) {
    
    
            return renderFailure("请输入电子责任书ID!");
        }
        String contentStr = "";
        if (StringUtil.isNotBlank(content)) {
    
    
            ObjectMapper objectMapper = new ObjectMapper();
            try {
    
    
                Map map = objectMapper.readValue(content, Map.class);
                contentStr = map.get("content").toString();
            } catch (IOException e) {
    
    
                e.printStackTrace();
                return renderFailure("电子责任书文本内容格式不正确,请重新输入!");
            }
        }
        RestResult restResult = renderSuccess();
        Boolean flag = service.editElectronicResponsibility(id, title, contentUrl, contentStr, comment);
        restResult.setMessage(flag ? "修改成功!" : "修改失败");
        return restResult;
    }

根据ServletRequestAttributes 获取前端请求方法名、参数、路径等信息

猜你喜欢

转载自blog.csdn.net/weixin_44412272/article/details/121613936