AOP给指定方法实现自定义业务

本篇文章以实际生产过程中处理极光推送消息后落地消息到数据库为例!
1.自定义需要推送后保存消息的注解

import java.lang.annotation.*;

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Message {

    /**
     * 是否需要保存消息日志,缺省为需要
     * @return
     */
    boolean saveMessage() default true;
}

2.实现消息切面

import com.ouyeel.ssx.common.annotation.Message;
import com.ouyeel.ssx.common.dto.MessageParam;
import com.ouyeel.ssx.common.service.MessageService;
import lombok.extern.slf4j.Slf4j;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Aspect
@Component
public class MessageAspect {

    @Autowired
    private MessageService messageService;
    @Pointcut("@annotation(com.ouyeel.ssx.common.annotation.Message)")
    public void pointcut() {
        // do nothing
    }
    //保存推送消息日志
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Message messageAnnotation = method.getAnnotation(Message.class);
        Object result = point.proceed();
        if(messageAnnotation.saveMessage()){
            int success = 0;
            if(1 == (int) result){
                success = 1;
            }
            try {
                if(point.getArgs() != null && point.getArgs().length > 0){
                    for (Object o : point.getArgs()) {
                        if(o != null && o instanceof MessageParam){
                            MessageParam m = (MessageParam)o;
                            m.setIsSuccess(success);
                            messageService.saveBatchMessage(m);
                            log.info("====【记录保存Message消息成功】result:success");
                        }
                    }
                }
            }catch (Exception e){
                log.error("=====【记录保存Message消息失败】error:{}",e.getMessage());
            }
        }
        return result;
    }
}

3.极光推送消息方法上增加自定义的消息注解

@Message
@Override
public int jpush(JPushCommonParam param) throws APIConnectionException, APIRequestException {
try {
	xxx
	return 1;
}catch(Exception e){
    	log.info("=======【推送失败】sendPush exception: "+e.getMessage());
}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值