springAop的简单应用

学习目标:

最近公司用springAop要做一个功能,就是用aop进行用户积分的加减,就用aop做了简单的配置和手续简单的实现
例如:

学习内容:

首先做的就是aop的配置,我们是公司自己封装的springBoot,具体配置看代码

package com.pixel.cloud.guard.handler;

import com.alibaba.fastjson.JSONObject;
import com.pixel.cloud.guard.api.integral.TGuardDeclareDetailsService;
import com.pixel.cloud.guard.model.request.integral.declare.AddDeclareDetailsReq;
import com.pixel.cloud.guard.server.util.IntegralTypeEnum;
import com.pixel.idaas.model.response.login.LoginInfoRes;
import com.uhomed.basic.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.jetbrains.annotations.NotNull;
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 org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


@Aspect
@Component
@Slf4j
public class IntegralPrintAspect {

    @Autowired
    private TGuardDeclareDetailsService declareDetailsService;

    /**
     * 以自定义 @IntegralPrint 注解为切点
     */
    @Pointcut("@annotation(com.pixel.cloud.guard.handler.IntegralPrint)")
    public void MyPrint() {
    }

    /**
     * 在切点之前织入
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Before("MyPrint()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if (attributes == null) {
            return;
        }

        String method=joinPoint.getSignature().getName();
        if("queryById".equals(method)){//查看文章
            Object arg = joinPoint.getArgs()[0];
            AddDeclareDetailsReq req=new AddDeclareDetailsReq();
            req.setType(IntegralTypeEnum.ARTICLE.getKey());
            req.setIntegralEventId((String)arg);
            declareDetailsService.addDeclareDetails(req);
        }

        if("drawTask".equals(method)){//领取任务
            AddDeclareDetailsReq req=new AddDeclareDetailsReq();
            req.setType(IntegralTypeEnum.TASK.getKey());
            declareDetailsService.addDeclareDetails(req);
        }

    }

    /**
     * 在切点之后织入
     *
     * @throws Throwable
     */
    @After("MyPrint()")
    public void doAfter() throws Throwable {
        /* 接口结束后换行,方便分割查看 */
        log.info("=========================================== End ===========================================");
    }

    /**
     * 环绕
     *
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("MyPrint()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object result = proceedingJoinPoint.proceed();
        String method=proceedingJoinPoint.getSignature().getName();
        if("loginMsgCode".equals(method)){//登陆获取积分;
            AddDeclareDetailsReq req=new AddDeclareDetailsReq();
            if (result instanceof Response) {
                Response<LoginInfoRes> loginInfoRes=(Response)result;
                req.setUserId(loginInfoRes.getRes().getId());
                req.setNickName(loginInfoRes.getRes().getUserName());
                req.setResidentName(loginInfoRes.getRes().getAccount());
                req.setAvatar(loginInfoRes.getRes().getAvatar());
                req.setTelnumber(loginInfoRes.getRes().getMobile());
            }
            req.setType(IntegralTypeEnum.LOGIN.getKey());
            declareDetailsService.addDeclareDetails(req);
        }
        if("jsCodeLogon".equals(method)){//授权获取积分
            AddDeclareDetailsReq req=new AddDeclareDetailsReq();
            if (result instanceof Response) {
                Response<LoginInfoRes> loginInfoRes=(Response)result;
                req.setUserId(loginInfoRes.getRes().getId());
                req.setNickName(loginInfoRes.getRes().getUserName());
                req.setResidentName(loginInfoRes.getRes().getAccount());
                req.setAvatar(loginInfoRes.getRes().getAvatar());
                req.setTelnumber(loginInfoRes.getRes().getMobile());
            }
            req.setType(IntegralTypeEnum.LOGIN.getKey());
            req.setTypeName("授权登陆");
            declareDetailsService.addDeclareDetails(req);
        }
        if("endPatrolRecord".equals(method)){//巡防打卡
            AddDeclareDetailsReq req=new AddDeclareDetailsReq();
            req.setType(IntegralTypeEnum.PATROL.getKey());
            declareDetailsService.addDeclareDetails(req);
        }
        if("addEvent".equals(method)){//事件上报
            AddDeclareDetailsReq req=new AddDeclareDetailsReq();
            req.setType(IntegralTypeEnum.EVENT.getKey());
            declareDetailsService.addDeclareDetails(req);
        }
        if("addTask".equals(method)){//事件发布
            AddDeclareDetailsReq req=new AddDeclareDetailsReq();
            req.setType(IntegralTypeEnum.EVENT.getKey());
            req.setTypeName("发布");
            declareDetailsService.addDeclareDetails(req);
        }
        return result;
    }


    /**
     * 获取切面注解的描述
     *
     * @param joinPoint 切点
     * @return 描述信息
     * @throws Exception
     */
    public String getAspectLogDescription(JoinPoint joinPoint)
            throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        StringBuilder description = new StringBuilder("");
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description.append(method.getAnnotation(IntegralPrint.class).description());
                    break;
                }
            }
        }
        return description.toString();
    }

    private String getParams(@NotNull JoinPoint joinPoint) {
        String params = "";
        if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
            for (int i = 0; i < joinPoint.getArgs().length; i++) {
                Object arg = joinPoint.getArgs()[i];
                if ((arg instanceof HttpServletResponse) || (arg instanceof HttpServletRequest)
                        || (arg instanceof MultipartFile) || (arg instanceof MultipartFile[])) {
                    continue;
                }
                try {
                    params += JSONObject.toJSONString(joinPoint.getArgs()[i]);
                } catch (Exception e1) {
                    log.error(e1.getMessage());
                }
            }
        }
        return params;
    }
}
  1. 接下来就是具体的业务代码
private void loginAddDeclare(AddDeclareDetailsReq req){
        TGuardDeclareDetailsEntity entity=new TGuardDeclareDetailsEntity();
        entity.setIntegralEvent(IntegralTypeEnum.LOGIN.getValue());
        entity.setName(IntegralTypeEnum.LOGIN.getValue());
        entity.setApprovalStatus(1);
        if("授权登陆".equals(req.getTypeName())){
            entity.setPointsChange(queryDeclareSet("用户授权登录青山云卫士"));
        }else{
            entity.setPointsChange(queryDeclareSet("用户手机号登录青山云卫士"));
        }
        LoginInfoRes loginInfoRes=new LoginInfoRes();
        loginInfoRes.setId(req.getUserId());
        loginInfoRes.setUserName(req.getNickName());
        loginInfoRes.setAccount(req.getResidentName());
        loginInfoRes.setAvatar(req.getAvatar());
        loginInfoRes.setMobile(req.getTelnumber());
        List<Condition> conditions = new ArrayList<>();
        conditions.add(Condition.eq("userId",loginInfoRes.getId()));
        Where whereConditions =Where.part(ConditionPart.content(conditions));
        int num=dsClient.queryCount(TCreditAccountEntity.class,whereConditions).intValue();
        if(num==0){
            TCreditAccountEntity accountEntity=new TCreditAccountEntity();
            accountEntity.setId(ID.get());
            accountEntity.setUserId(loginInfoRes.getId());
            accountEntity.setUserName(loginInfoRes.getUserName());
            accountEntity.setMobile(loginInfoRes.getMobile());
            accountEntity.setCreateTime(new Date());
            accountEntity.setUpdateTime(new Date());
            dsClient.insert(accountEntity);
        }
        addDeclareDetails(entity,loginInfoRes);
    }

    private void articleAddDeclare(String articleId){
        LoginInfoRes loginInfoRes = sessionHandler.get();
        List<Condition> conditions = new ArrayList<>();
        conditions.add(Condition.eq("integralEventId",articleId));
        conditions.add(Condition.eq("userId",loginInfoRes.getId()));
        Where whereConditions =Where.part(ConditionPart.content(conditions));
        int num=dsClient.queryCount(TGuardDeclareDetailsEntity.class,whereConditions).intValue();
        if(num==0){
            TGuardDeclareDetailsEntity entity=new TGuardDeclareDetailsEntity();
            entity.setIntegralEvent(IntegralTypeEnum.ARTICLE.getValue());
            entity.setName(IntegralTypeEnum.ARTICLE.getValue());
            entity.setIntegralEventId(articleId);
            entity.setApprovalStatus(1);
            entity.setPointsChange(queryDeclareSet("阅读一次青山云卫士文章"));
            addDeclareDetails(entity,loginInfoRes);
        }

    }

    private void eventAddDeclare(String typeName){
        LoginInfoRes loginInfoRes = sessionHandler.get();
        TGuardDeclareDetailsEntity entity=new TGuardDeclareDetailsEntity();
        entity.setIntegralEvent(IntegralTypeEnum.EVENT.getValue());
        entity.setName(IntegralTypeEnum.EVENT.getValue());
        entity.setApprovalStatus(1);
        if("发布".equals(typeName)){
            entity.setPointsChange(queryDeclareSet("事件报料选中发布后"));
        }else{
            entity.setPointsChange(queryDeclareSet("事件报料提交成功后"));
        }
        addDeclareDetails(entity,loginInfoRes);

    }

    private void taskAddDeclare(){
        LoginInfoRes loginInfoRes = sessionHandler.get();
        TGuardDeclareDetailsEntity entity=new TGuardDeclareDetailsEntity();
        entity.setIntegralEvent(IntegralTypeEnum.TASK.getValue());
        entity.setName(IntegralTypeEnum.TASK.getValue());
        entity.setApprovalStatus(1);
        entity.setPointsChange(queryDeclareSet("领取并完成社区任务后"));
        addDeclareDetails(entity,loginInfoRes);

    }

    private void patrolAddDeclare(){
        LoginInfoRes loginInfoRes = sessionHandler.get();
        TGuardDeclareDetailsEntity entity=new TGuardDeclareDetailsEntity();
        entity.setIntegralEvent(IntegralTypeEnum.PATROL.getValue());
        entity.setName("巡防打卡");
        entity.setApprovalStatus(1);
        entity.setPointsChange(queryDeclareSet("完成第一个点打卡"));
        addDeclareDetails(entity,loginInfoRes);

    }

    private void addDeclareDetails(TGuardDeclareDetailsEntity entity,LoginInfoRes loginInfoRes){
        entity.setUserId(loginInfoRes.getId());
        entity.setNickName(loginInfoRes.getUserName());
        entity.setResidentName(loginInfoRes.getAccount());
        entity.setAvatar(loginInfoRes.getAvatar());
        entity.setTelnumber(loginInfoRes.getMobile());
        entity.setId(ID.get());
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        dsClient.saveOne(entity);
        List<Condition> conditions = new ArrayList<>();
        conditions.add(Condition.eq("userId",loginInfoRes.getId()));
        Where whereConditions =Where.part(ConditionPart.content(conditions));
        whereConditions.limit(1,1);
        List<TCreditAccountEntity> list=dsClient.queryPage(TCreditAccountEntity.class,whereConditions).getData();
        if(list!=null&&list.size()>0){
            int creditNum=list.get(0).getCreditTotal();
            creditNum=creditNum+entity.getPointsChange();
            TCreditAccountEntity accountEntity=new TCreditAccountEntity();
            accountEntity.setCreditTotal(creditNum);
            accountEntity.setUpdateTime(new Date());
            accountEntity.setVersion(list.get(0).getVersion()+1);
            List<Condition> condition = new ArrayList<>();
            condition.add(Condition.eq("userId",loginInfoRes.getId()));
            condition.add(Condition.eq("version",list.get(0).getVersion()));
            UpdateWhere updateConditions =UpdateWhere.part(ConditionPart.content(condition));
            dsClient.batchUpdate(accountEntity,TCreditAccountEntity.class,updateConditions);
        }

    }

    private int queryDeclareSet(String name){
        List<Condition> conditions = new ArrayList<>();
        conditions.add(Condition.eq("type",name));
        Where whereConditions = CollUtil.isEmpty(conditions) ? Where.part() : Where.part(ConditionPart.content(conditions));
        whereConditions.limit(1, 1);
        com.pixel.datastore.sdk.bean.query.Paging<TCreditSetEntity> tGuardArticleEntityPaging = dsClient.queryPage(TCreditSetEntity.class, whereConditions);
        List<TCreditSetEntity> data = tGuardArticleEntityPaging.getData();
        return data.get(0).getCredit();
    }

2.具体调用就是采用注解


    /**
     * 以自定义 @IntegralPrint 注解为切点
     * 这里是自定义的注解,作用在controller的方法上
     * 识别动作的
     */
    @Pointcut("@annotation(com.pixel.cloud.guard.handler.IntegralPrint)")
    public void MyPrint() {
    }
  1. 接下来就是具体的调用方法,去获取动作,然后对方法进行匹配
    /**
     * 小程序端文章活动详情
     * @param id
     * @return
     */
    @ApiOperation("小程序端查询文章详情")
    @GetMapping("/queryById")
    @IntegralPrint
    public Response<ArticleListRes> queryById(String id) {
        ArticleListRes articleListRes = tGuardArticleService.queryById(id);
        return  Response.ok(articleListRes);
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值