使用aop在某个方法返回时触发逻辑

自定义注解

package com.minex.icp.v3.module.devicealarm.aop;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/*
 *  自动发送消息通知
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface PushScadaAlarmList {
    String value() default "";
}

指定切点

package com.minex.icp.v3.module.devicealarm.aop;

import com.minex.icp.v3.module.devicealarm.service.RealTimeDataService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * @Description: 推送Scada告警列表数据
 * @Author: gch
 * @Date: 2024/4/17 11:20
 */
@Aspect
@Component
@Slf4j
public class PushScadaAlarmListAspect {

    @Resource
    private RealTimeDataService realTimeDataService;

    /**
     * 配置织入点
     */
    @Pointcut("@annotation(com.minex.icp.v3.module.devicealarm.aop.PushScadaAlarmList)")
    public void pointCut() { }

    /**
     * 处理完请求后执行
     */
    @AfterReturning(pointcut = "pointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        // 获得注解
        PushScadaAlarmList pushScadaAlarmList = getAnnotation(joinPoint);
        if (pushScadaAlarmList == null) {
            return;
        }
        String value = pushScadaAlarmList.value();
        try {
            // 指定方法调用成功后推送告警消息
            realTimeDataService.pushScadaAlarmList();
        } catch (Exception e) {
            log.error("异常信息为:", e);
        }

    }

    /**
     * 拦截异常操作
     */
    @AfterThrowing(value = "pointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleException(joinPoint, e);
    }

    public void handleException(final JoinPoint joinPoint, final Exception e) {
        // 获得注解
        PushScadaAlarmList pushScadaAlarmList = getAnnotation(joinPoint);
        if (pushScadaAlarmList == null) {
            return;
        }
        String value = pushScadaAlarmList.value();
        log.error("异常信息为:{}", e);
    }

    /**
     * 获取存在的注解
     */
    private PushScadaAlarmList getAnnotation(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(PushScadaAlarmList.class);
        }
        return null;
    }
}

 

posted @ 2024-04-17 11:28  官萧何  阅读(24)  评论(0)    收藏  举报