Spring spel获取自定义注解参数值

时间:2025-02-16 07:18:49

1.注解类

package ;

import .*;

/**
 * 库存不足等信息监控
 * Created by xdc on 2019/4/16 15:43
 */
@Retention()
@Target({})
@Documented
public @interface StockWarnCollect {

    /** 客户id */
    String customerId();

    /** 来源 */
    String source();

    /** 请求类型 1:详情页 2:购物车去结算 3:提交订单 */
    String pageType();
}

2.注解使用

@Override
@StockWarnCollect(customerId = "#customerId", source = "#source", pageType = "2")
public Map<String, Object> validateCarts(Long customerId, Set<Long> userSelectedIds, Short source, JSONArray couponInfo){
    // 省略
}

中处理

import .slf4j.Slf4j;
import ;
import .;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

/**
 * 下单失败、库存监控
 * Created by xdc on 2019/4/16 15:45
 */
@Aspect
@Component
@Slf4j
public class StockWarnCollectAop {

    @Pointcut(value = "@annotation()")
    public void collectStockWarn(){}

    @Around(value = "collectStockWarn()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        Method targetMethod = (pjp);
        StockWarnCollect stockWarnCollect = ();

        // spel信息
        String customerIdSpel = ();
        String sourceSpel = ();
        Integer pageType = null;  // 操作类型,纯字符串
        if ((())) {
            pageType = (());
        }

        // 客户id、来源解析
        ExpressionParser parser = new SpelExpressionParser();
        LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
        String[] params = (targetMethod);

        Object[] args = ();

        EvaluationContext context = new StandardEvaluationContext();
        for (int len = 0; len < ; len++) {
            (params[len], args[len]);
        }
        Expression expression = (customerIdSpel);
        Long customerId = (context, );

        expression = (sourceSpel);
        Short source = (context, );
        ("collectStockWarn customerId:{}, source:{}", customerId, source);

        // 业务逻辑处理
        Object result = null;
        try {
            result = ();
        } catch (Throwable e) {
            ("collectStockWarn watchs creating order errorMsg:{}", (e));
            if (e instanceof MallException) {

            } else {    // 未知错误
            
            }

            throw e;
        }

        try {
            if (result != null) {
            
            }
        } catch (Exception e) {
            ("collectStockWarn process error, errorMsg:{}", (e));
        }

        return result;

    }

    /**
     * 获取目标方法
     */
    private Method getTargetMethod(ProceedingJoinPoint pjp) throws NoSuchMethodException {
        Signature signature = ();
        MethodSignature methodSignature = (MethodSignature)signature;
        Method agentMethod = ();
        return ().getClass().getMethod((),());
    }
}