首页 > 编程语言 > 详细

Spring AOP 结合自定义注解的使用

时间:2019-03-07 10:59:09      阅读:182      评论:0      收藏:0      [点我收藏+]

例如要实现一个评论内容的拦截

1,声明自定义注解,这里的key()为要拦截的方法中的方法体对应的变量名,可以参考第3点.

技术分享图片

2,创建一个切面类,@annatation()中的comment 为方法参数体中的注解对应的变量名

技术分享图片

 

 3,在要拦截的方法上加入定义好的注解,其中#comment使用的是spel表达式.

 技术分享图片

Spel表达式工具类:

package club.ruanx.util;

import org.springframework.expression.spel.standard.SpelExpression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.util.StringUtils;

/**
 * Spel表达式工具类
 *
 * @author 阮胜
 * @date 2018/12/20 20:36
 */
public class SpelUtils {

    /**
     * 解析Spel表达式
     * 例如: SpelUtils.parseExpression("‘Hello ‘+#msg", new String[]{"msg"}, new Object[]{"World"});
     * 其中 #msg是变量,把对应的参数列表的值依次填充到各个变量中
     *
     * @param expression     表达式
     * @param parameterNames 参数名称
     * @param args           参数值
     * @return 解析后的表达式
     */
    public static String parseExpression(String expression, String[] parameterNames, Object[] args) {
        if (StringUtils.isEmpty(expression) || parameterNames == null || args == null
                || parameterNames.length != args.length) {
            return expression;
        }
        SpelExpression spelExpression = new SpelExpressionParser().parseRaw(expression);
        StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
        for (int i = 0; i < parameterNames.length; i++) {
            evaluationContext.setVariable(parameterNames[i], args[i]);
        }
        spelExpression.setEvaluationContext(evaluationContext);
        return spelExpression.getValue(String.class);
    }
}

 

 

切面工具类:

package club.ruanx.util;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;

import java.lang.reflect.Method;

/**
 * @author 阮胜
 * @date 2018/12/20 20:30
 */
public class AspectUtils {

    /**
     * 根据切入点获取方法的形参列表
     *
     * @param joinPoint 切入点
     * @return 形参列表
     */
    public static String[] getMethodParamNames(JoinPoint joinPoint) {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        return getMethodParamNames(method);
    }

    /**
     * 根据方法获取形参列表
     *
     * @param method 方法
     * @return 形参列表
     */
    public static String[] getMethodParamNames(Method method) {
        return new LocalVariableTableParameterNameDiscoverer().getParameterNames(method);
    }
}

 

Spring AOP 结合自定义注解的使用

原文:https://www.cnblogs.com/cearnach/p/10487897.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!